public static void main(String... ar)
{
Thread newThread = new Thread("Thread2"); //line1
newThread.start(); //line2
newThread.join(); //line3
System.out.println("Hello from main");
}
Method | Description |
---|---|
final void join() | This version of join() method makes a thread wait for another thread to finish its execution. |
final void join(long millis) | This version of join() method a thread wait only for a specified time(in milliseconds) for another thread to finish its execution. |
class ThJoin implements Runnable
{
public void run() //Entry Point of the new thread.
{
Thread th=Thread.currentThread(); //Getting the reference to the currently executing thread.
try
{
for(int i=0;i<3;i++)
{
Thread.sleep(1000); //This will make this thread sleep for 1000 ms.
System.out.println(i);
}
System.out.println(th.getName() + " completed");
}
catch(InterruptedException e)
{
System.out.println("Thread Interrupted" + e);
}
}
public static void main(String... ar)
{
ThJoin newTh= new ThJoin();
Thread th= new Thread(newTh, "OtherThread");//Calling Thread's constructor & passing the object
//of class that implemented Runnable interface
//& the name of new thread.
th.start();
try
{
th.join(); //main thread will wait for other thread to complete its execution and join it.
System.out.println("Main thread ends");
}
catch(InterruptedException e)
{
System.out.println(e);
}
}
}
0
1
2
Other Thread completed
Main thread completed
Coming Next
-
Python