CountDownLatch 使用场景

/**
 * 第一个使用场景
 * 数据使用多线程的方式处理
 */
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 方法处理即可
 */

发布了68 篇原创文章 · 获赞 6 · 访问量 6666

猜你喜欢

转载自blog.csdn.net/renguiriyue/article/details/104886706