1. 程式人生 > 其它 >CountDownLatch執行緒池主執行緒同步

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!