java 中的CountDownLatch

直接使用thread可以使用thread和wait notify 实现顺序执行

线程池中可以使用CountDownLatch 进行顺序执行

package com.test;

import java.util.concurrent.CountDownLatch;

public class Sample {
    /**
     * 计数器,用来控制线程
     * 传入参数2,表示计数器计数为2
     */
    private final static CountDownLatch mCountDownLatch = new CountDownLatch(2);

    /**
     * 示例工作线程类
     */
    private static class WorkingThread extends Thread {
        private final String mThreadName;
        private final int mSleepTime;
        public WorkingThread(String name, int sleepTime) {
            mThreadName = name;
            mSleepTime = sleepTime;
        }

        @Override
        public void run() {
            System.out.println("[" + mThreadName + "] started!");
            try {
                Thread.sleep(mSleepTime);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            mCountDownLatch.countDown();
            System.out.println("[" + mThreadName + "] end!");
        }
    }

    /**
     * 示例线程类
     */
    private static class SampleThread extends Thread {

        @Override
        public void run() {
            System.out.println("[SampleThread] started!");
            try {
                // 会阻塞在这里等待 mCountDownLatch 里的count变为0;
                // 也就是等待另外的WorkingThread调用countDown()
                mCountDownLatch.await();
            } catch (InterruptedException e) {

            }
            System.out.println("[SampleThread] end!");
        }
    }

    public static void main(String[] args) throws Exception {
        // 最先run SampleThread
        new SampleThread().start();
        // 运行两个工作线程
        // 工作线程1运行5秒
        new WorkingThread("WorkingThread1", 5000).start();
        // 工作线程2运行2秒
        new WorkingThread("WorkingThread2", 2000).start();
    }
}

 

转自 https://www.cnblogs.com/flyme/p/4568063.html

posted @ 2018-01-11 14:42  甜菜波波  阅读(184)  评论(0编辑  收藏  举报