CountDownLatch_demo

发布时间 2023-06-13 15:26:23作者: hemeiwolong

参考:

https://zhuanlan.zhihu.com/p/95835099

https://www.cnblogs.com/blogtech/p/16270225.html

https://www.cnblogs.com/dafanjoy/p/9729358.html

Service.java

package com.hmb;

import java.util.concurrent.CountDownLatch;

public class Service implements Runnable{
    private CountDownLatch latch;

    public Service(CountDownLatch latch) {
        this.latch = latch;
    }

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName() + " execute task...");
        try {
            Thread.sleep(2000);
            System.out.println(Thread.currentThread().getName() + "finished task");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            latch.countDown();
        }
    }
}

  

ThreadUtils.java

package com.hmb;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class ThreadUtils {
    private static ExecutorService executorService;

    static {
        executorService = new ThreadPoolExecutor(Runtime.getRuntime().availableProcessors() * 2 + 1,
            Runtime.getRuntime().availableProcessors() * 2 + 1,
            0L, TimeUnit.MILLISECONDS,
            new LinkedBlockingQueue<>(10000));
    }

    public static void execute(Runnable task) {
        executorService.execute(task);
    }
}

  

Main.java

package com.hmb;

import java.util.concurrent.CountDownLatch;

public class Main {
    public static void main(String[] args) {
        int taskNum = 5;
        CountDownLatch latch = new CountDownLatch(taskNum);

        long start = System.currentTimeMillis();
        for (int i = 0; i < taskNum; i++) {
            ThreadUtils.execute(new Service(latch));
        }
        try {
            latch.await();
            long end = System.currentTimeMillis();
            System.out.println("spend time: " + (end - start) + "ms");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

  

运行结果: