/**
* 第一個使用場景
* 數據使用多線程的方式處理
*/
public class CountDownLatchTest {
private static ExecutorService executor = newFixedThreadPool(2);
private static final CountDownLatch latch = new CountDownLatch(10);
public static void main(String[] args) throws InterruptedException {
int[] data = query();
for(int i = 0;i < data.length ; i++){
executor.submit(new SimpleThread(data,latch,i));
}
executor.shutdown();
latch.await();
System.out.println("main thread end");
}
public static int[] query(){
return new int[]{1,2,3,4,5,6,7,8,9,10};
}
}
class SimpleThread extends Thread{
private final int[] data;
private final CountDownLatch latch;
private final int i;
public SimpleThread(int[] data, CountDownLatch latch, int i) {
this.data = data;
this.latch = latch;
this.i = i;
}
@Override
public void run() {
try {
Thread.sleep(1000);
latch.countDown();
if(data[i] % 2 == 0){
data[i] = data[i] + 10;
}
System.out.println(Thread.currentThread().getName() + " " + data[i]);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
/**
* 第二個使用場景,就是當一個任務做完的時候,在第二個任務執行一半的時候需要用到第一個任務的結果集
* 那麼在第二個任務使用 await 方法處理即可
*/
CountDownLatch 使用場景
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.