Merxe
Merxe

Reputation: 21

printing threads in strict order

I am trying to print threads in specific order. So I have a main method which starts 10 threads. I need to print in the following order:

main thread started

thread 0 started thread 1 started . . thread 9 started

thread 0 finished thread 1 finished . . . thread 9 finished

main thread finished

I have tried with join() method where main thread joins after each thread has started and finished.

This only solves half the problem. I also need to print start of each thread and then finished of each new thread.

Any suggestions.

Upvotes: 2

Views: 218

Answers (1)

Adriaan Koster
Adriaan Koster

Reputation: 16209

You don't need any synchronization constructs (was that a requirement? I think it should be to make this more interesting). You can do it simply like this:

public class ThreadOrder {

    public static class WaitingForMyTurn extends Thread {

        private static volatile Integer currentNumber = 1;
        private Integer myNumber;

        public WaitingForMyTurn(Integer number) {
            this.myNumber = number;
        }

        public void run() {
            while (currentNumber < myNumber) {
            }
            System.out.println(myNumber);
            currentNumber = myNumber + 1;
        }
    }

    public static void main(String[] args) {

        for (int i = 0; i < 10; i++) {
            new WaitingForMyTurn(i).start();
        }
    }
}

EDIT: made currentNumber volatile

Upvotes: 2

Related Questions