多線程使用記錄

1.CountDownLatch的平常使用。

當咱們須要兩個線程或多個線程同時執行任務時,而且在執行完子線程以後,再執行主線程,能夠利用CountDownLatchide

public static void main(String[] args) {
	final CountDownLatch countDownLatch= new CountDownLatch(2);//等子線程處理完成後進行主線程操做
    testManyThread(countDownLatch);
    testManyThread(countDownLatch);
    try {
			countDownLatch.await();//阻塞當前線程直到latch中數值爲零才執行
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
    
}
private void testManyThread(CountDownLatch countDownLatch){
		new Thread(new Runnable() {
			@Override
			public void run() {
				countDownLatch.countDown();
			}
		}).start();
}
相關文章
相關標籤/搜索