Reputation: 1139
I am new to multithreading in java and I am trying to write a simple program to simulate inter-thread communication.
The problem is that my main
method is not terminating until I swap the below two lines.
t1.start();// if I call t2.start() first and then t1.start() then it works perfectly
t2.start();
Can someone please explain why do I need to call t2.start() before t1.start()?
Here's my code
public class WaitNotifyExample {
public static void main(String[] args) throws InterruptedException {
System.out.println("main method starts");
A a = new A();
Thread t1 = new Thread(new Runnable() {
public void run() {
try {
a.printNumbers();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
Thread t2 = new Thread(new Runnable() {
public void run() {
try {
a.afterPrintNumbers();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
// This works fine but I don't understand why..
t2.start();
t1.start();
t1.join();
t2.join();
System.out.println("main method ends");
}
}
class A{
public void printNumbers() throws InterruptedException{
synchronized(this){
for(int i = 0;i<10;i++){
System.out.println(i);
}
this.notify();
}
}
public void afterPrintNumbers() throws InterruptedException{
synchronized(this){
this.wait();
System.out.println("all no. printed");
}
}
}
Upvotes: 0
Views: 86
Reputation: 11
The order of the thread execution is not guaranteed and it depends on thread scheduler algorithm.
So In your case JVM is picking t1 and completes executing this.notify()
before t2 executes this.wait()
as mentioned earlier.
Upvotes: 1
Reputation: 28279
if I call t2.start() first and then t1.start() then it works perfectly
Not guaranteed.
Just consider, t1
execute this.notify();
first, then t2
execute this.wait();
.
In this situation, t2
will never get signal.
Upvotes: 3