1.Introduction to CountDownLatch

CountDownLatch is often used to monitor certain initialization operations, and notify the current thread to continue working after the initialization operation is completed.

In the following code, thread 1 will block at countDown.await() and need to wait for threads 2 and 3

import java.util.concurrent.CountDownLatch;

public class P01CountDownLatch
{
    public static void main(String[] args)
    {
        //2 means to wait for countDown() twice
        final CountDownLatch countDown = new CountDownLatch(2);
        Thread t1 = new Thread(new Runnable()
        {
            @Override
            public void run()
            {
                try
                {   
                    System.out.println("Enter thread t1, waiting for other threads to finish processing");
                    countDown.await();//Need to wait
                    System.out.println("t1 thread continues to execute");
                }
                catch (InterruptedException e)
                {
                    // TODO Auto-generated catch block
                    e.printStackTrace ();
                }
                
            }
        });
        Thread t2 = new Thread(new Runnable()
        {
            @Override
            public void run()
            {
                try
                {
                    System.out.println("Enter thread t2");
                    Thread.sleep(2000);
                    countDown.countDown();
                    System.out.println("The t2 thread is executed, notify the t1 thread to continue executing");
                }
                catch (InterruptedException e)
                {
                    // TODO Auto-generated catch block
                    e.printStackTrace ();
                }
               
                       
            }
        });
        Thread t3 = new Thread(new Runnable()
        {
            @Override
            public void run()
            {
                try
                {
                    System.out.println("Enter thread t3");
                    Thread.sleep(3000);
                    countDown.countDown();//If this line is commented out, the t1 thread will never execute again
                    System.out.println("The t3 thread is executed, notify the t1 thread to continue executing");
                }
                catch (InterruptedException e)
                {
                    // TODO Auto-generated catch block
                    e.printStackTrace ();
                }
               
                       
            }
        });
        t1.start();
        t2.start();
        t3.start();
    }
}


Results of the:

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325506893&siteId=291194637