Thread.sleep() can ditch your join()’s expected code execution , see it how !!


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

*/

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s