Reputation: 365
Following is code from OCJP exam
class Test implements Runnable{
synchronized void hit(long n) {
for(int i = 1; i < 3; i++)
System.out.print(n + "-" + i + " ");
}
public static void main(String... args) throws Exception{
new Thread(new Test()).start();
new Thread(new Test()).start();
}
@Override
public void run() {
hit(Thread.currentThread().getId());
}
}
Answer: 8-1 7-1 7-2 8-2 and
8-1 8-2 7-1 7-2
How this output is predicted?
Upvotes: 1
Views: 251
Reputation: 41188
You can't predict it. The threads are running in parallel and the output order will be effectively random between the threads although the order will be deterministic on each individual thread.
The synchronized on hit() is also doing nothing as each thread has its own Test object so is only synchronizing with itself.
In other words 8-2 will always follow 8-1. 7-2 will always follow 7-1, but the order of all the 7s is completely separate from the order of all the 8s. This means that given a set of possible outputs you can say that some are impossible and some are possible, you cannot predict what actual output will be produced though.
You should also read this question and the answers to it, very informative on this subject:
How do you think through and predict the output of a threading question like this?
Upvotes: 8
Reputation: 3084
You can't predict it, but you can set Thread's name yourself with some kind of counter (if that means anything to you).
Thread myThread = new Test();
myThread.setName(counter++);
Upvotes: 1