Java multithreading -- let the main thread wait for the sub-thread to finish executing, java Multithreading

Source: Internet
Author: User

Java multithreading -- let the main thread wait for the sub-thread to finish executing, java Multithreading

When using Java multi-threaded programming, the main thread often needs to wait until the sub-thread completes execution before it can continue to run. Next we will introduce a simple way to wait for the main thread.

Java. util. concurrent. CountDownLatch

The countDownLatch. await () method is very simple to complete the waiting of the main thread:

public class ThreadWait {    public static void main(String[] args) throws InterruptedException {        int threadNumber = 10;        final CountDownLatch countDownLatch = new CountDownLatch(threadNumber);        for (int i = 0; i < threadNumber; i++) {            final int threadID = i;            new Thread() {                public void run() {                    try {                        Thread.sleep(1000);                    } catch (InterruptedException e) {                        e.printStackTrace();                    }                    System.out.println(String.format("threadID:[%s] finished!!", threadID));                    countDownLatch.countDown();                }            }.start();        }        countDownLatch.await();        System.out.println("main thread finished!!");    }}

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.