CountDownLatch线程池主线程同步

1.创建实现类

package com.kerwin.grpc.server.thread;

import java.util.concurrent.CountDownLatch;

public class DogThread implements Runnable {

    private final CountDownLatch latch;

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

    @Override
    public void run() {
        System.out.println("this is thread: " + Thread.currentThread().getName());
        latch.countDown();
    }
}

2.测试CountDownLatch

package com.kerwin.grpc.server.thread;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class TestThreadPool {
    public static void main(String[] args) {
        ExecutorService service = Executors.newFixedThreadPool(3);
        CountDownLatch latch = new CountDownLatch(3);
        for (int i = 0; i < 3; i++) {
            service.execute(new DogThread(latch));
        }
        try {
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        service.shutdown();
        System.out.println("this is main thread!");
    }
}

3.结果

this is thread: pool-1-thread-1
this is thread: pool-1-thread-3
this is thread: pool-1-thread-2
this is main thread!

 

posted @ 2021-07-01 15:31  平山雪飞侠  阅读(119)  评论(0)    收藏  举报