public class JoinWithSleep
{
public static void main(String[] args)
{
Thread t1 = new Thread(() -> {
System.out.println(" In :: Thread t1");
});
Thread t2 = new Thread(() -> {
System.out.println(" In :: Thread t2");
try
{
t1.join();
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(" Out :: Thread t2");
});
try
{
t2.join();
}
catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
t2.start();
// this single sleep can ruin your code !!
try
{
Thread.sleep(4000);
}
catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
t1.start();
}
}
/*
Without Sleep
In :: Thread t2
In :: Thread t1
Out :: Thread t2
With Sleep
In :: Thread t2
Out :: Thread t2
In :: Thread t1
*/
Like this:
Like Loading...
Related