I found below code for replicating the join() behavior in Java. There are two possible execution path:
- When Main thread continues execution and enters into the synchronized block. It then has to wait for thread t to finish.
- When Thread t starts first and calls the run method, then Main thread waits to acquire the lock.
In both the scenarios there is no notify() but still program completes with appropriate output. Can you please let me know why Main thread is not waiting forever as there is no notify()?
public class SequentialTreadWithoutJoin {
public static void main(String[] args) {
MyThread t = new MyThread("myThread");
t.start();
synchronized(t){
try {
System.out.println("Before wait");
t.wait();
System.out.println("After wait");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
for(int i = 0; i < 10; i++)
System.out.println("Thread " + Thread.currentThread().getName() + " will continue after join and print : " + i );
}
}
class MyThread extends Thread{
public MyThread(String name) {
super(name);
}
public synchronized void run(){
System.out.println("Thread " + this.getName() + " will run for 1 minute");
try {
this.sleep(60000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}