闭锁(CountDownLatch)

package japan.example.test;

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

public class CountDownLatchTest {

    public static void main(String[] args) throws Exception {

        CountDownLatchTest test = new CountDownLatchTest();
        test.test();
    }

    public void test() throws InterruptedException {
        int nthread = 5;
        ExecutorService service = Executors.newFixedThreadPool(nthread);

        CountDownLatch latch = new CountDownLatch(nthread);

        for (int i = 0; i < nthread; i++) {
            service.execute(new Runner(latch));
        }

        latch.await();

        service.shutdown();
        while (!service.isTerminated()) {
            try {
                // 用于等待子线程结束,再继续执行下面的代码
                service.awaitTermination(5, TimeUnit.SECONDS);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }

}

class Runner implements Runnable {

    CountDownLatch latch;

    Runner(CountDownLatch latch) {
        this.latch = latch;
    }

    @Override
    public void run() {
        try {
            // dosomething
            System.err.println("say hello!");
        } finally {
            latch.countDown();
        }
    }

}

 

posted on 2018-02-12 16:09  jis117  阅读(336)  评论(0编辑  收藏  举报

导航