JAVA multi-thread CountDownLatch usage details,

Source: Internet
Author: User

JAVA multi-thread CountDownLatch usage details,

Preface:

The test last week raised a bug for the module developed by the development colleagues, and it was still a coincidence.

After carefully checking the code, we found that multithreading was enabled in the business, and two threads ran simultaneously. However, the newly started two threads must ensure that one thread was completed and the other thread continued to run, to eliminate bugs.

When will it be used?

Multithreading is used in many places. However, if we want to start another thread after a specific thread runs, CountDownLatch can be used in this case.

How to use it?

Let's take a look at the common multi-threaded code:

package code;public class MyThread extends Thread {   public static void main(String[] args) {       MyThread th = new MyThread();      Thread t1 = new Thread(th, "Mythread");        t1.start();     System.out.println(Thread.currentThread().getName());     }        public void run()       {           Mythread1 th2 = new Mythread1();          Thread t2 = new Thread(th2, "Mythread1");            t2.start();         System.out.println(this.currentThread().getName());       }     class Mythread1 extends Thread    {      public void run() {          try {          Thread.sleep(1000);        } catch (InterruptedException e) {          // TODO Auto-generated catch block          e.printStackTrace();        }        System.out.println(this.currentThread().getName());         }           }  }

The code above uses MyThread to inherit the Thread class, and then writes a MyThread1 class in the MyThread class. It also inherits the Thread class and sleeps for 1 second in the run method, in this way, the code will be printed:

From the output sequence, we can see that the main thread is started first, then the MyThread thread is started again, and the MyThread1 thread is started again in the MyThread thread. However, the MyThread1 thread slept for 1 second to simulate the processing of subsequent services, which is later than the time when MyThread finished running.

Now, add CountDownLatch to the code. You need to finish running MyThread1 first and then continue running MyThread.

package code;import java.util.concurrent.CountDownLatch;public class MyThread extends Thread {   CountDownLatch countDownLatch = new CountDownLatch(1);  public static void main(String[] args) {       MyThread th = new MyThread();      Thread t1 = new Thread(th, "Mythread");        t1.start();     System.out.println(Thread.currentThread().getName());     }        public void run()       {           Mythread1 th2 = new Mythread1();          Thread t2 = new Thread(th2, "Mythread1");            t2.start();         try {          countDownLatch.await();        } catch (InterruptedException e) {          e.printStackTrace();        }        System.out.println(this.currentThread().getName());       }     class Mythread1 extends Thread    {      public void run() {          try {          Thread.sleep(1000);        } catch (InterruptedException e) {          e.printStackTrace();        }        System.out.println(this.currentThread().getName());         countDownLatch.countDown();        }           }  }

The code is written as shown above, roughly in three steps

1. Set the input parameter of a new CountDownLatch object to 1 (I personally understand this as if it is a new array. When will the array be cleared, then the interrupted thread can continue to run)

2. Call countDownLatch. await () in the MyThread class to stop the current thread.

3. Call the countDownLatch. countDown () method in the Mythread1 class. When Mythread1 is fully executed and the method is finally called, the function is to clear the "array" that I am talking about.

Check the output result.

The result is as expected.

Finally, we will call CountDownLatch countDownLatch = new CountDownLatch (1) as the input parameter. If this parameter is set to 1, we need to call countDownLatch. countDown () minus 1.

If it is another number, it is necessary to call the corresponding number of times, otherwise the thread that calls countDownLatch. await () will not continue to execute.

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.