If you want that one thread should waits until another thread return from its running process or it die You can do it by using the join() method. If join method is called then the execution stops on that line of code until the thread on which join() called is died .
//join
//Author @ Hemraj
class MyThread extends Thread
{
String msg;
MyThread(String msg)
{
this.msg=msg;
}
public void run()
{
for(int i=0;i<10;i++)
{
try
{
sleep(500);
}catch(InterruptedException e){}
System.out.println(i+msg);
}
}
}
class MyThrea
{
public static void main(String ar[])
{
MyThread t1=new MyThread("this is t1");
t1.start();
for(int i=0;i<10;i++)
{
try
{
Thread.sleep(500);
if(i==5)
{
try{t1.join();}catch(InterruptedException e){}
}
}catch(InterruptedException e){}
System.out.println(i+"main thread");
}
}
}
class MyThread extends Thread
{
String msg;
MyThread(String msg)
{
this.msg=msg;
}
public void run()
{
for(int i=0;i<10;i++)
{
try
{
sleep(500);
}catch(InterruptedException e){}
System.out.println(i+msg);
}
}
}
class MyThrea
{
public static void main(String ar[])
{
MyThread t1=new MyThread("this is t1");
t1.start();
for(int i=0;i<10;i++)
{
try
{
Thread.sleep(500);
if(i==5)
{
try{t1.join();}catch(InterruptedException e){}
}
}catch(InterruptedException e){}
System.out.println(i+"main thread");
}
}
}
Comments