Wait until all threads done

public void testThreadSync() {
    Thread[] threads = new Thread[TEST_THREAD_COUNT];
    final CountDownLatch latch = new CountDownLatch(TEST_THREAD_COUNT);
    for (int i = 0; i < TEST_THREAD_COUNT; i++) {
        threads[i] = new Thread(new Runnable() {    
            public void run() {
                try {
                    Thread.sleep(random.nextInt(100));
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                latch.countDown();
            }
        });
        threads[i].start();
    }
    try {
        latch.await();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

import java.util.concurrent.CountDownLatch;
import java.lang.Thread;
CountDownLatch mDoneSignal = new CountDownLatch(TOTAL_THREADS);
-----------------------------------------------------------------
 Thread thread = new Thread(new Runnable() { //anonymous function
@Override
public void run() {
//code
mDoneSignal.countDown();
}
})
;
Thread thread = new Thread(() -> {    //or lambda
//code
mDoneSignal.countDown();
});
-----------------------------------------------------------------
try {
mDoneSignal.await(); //await block, until CountDownLatch countDown from TOTAL_THREADS to 0, then all thread ending and go to next
}catch(InterruptedException e){
e.printStackTrace();
}

Reference
https://www.cnblogs.com/zl1991/p/6930160.html
posted @ 2021-08-30 14:03  最佳秋天  阅读(48)  评论(0)    收藏  举报