JAVA发令枪工具

发令枪

发令枪即准备N位选手,进行准备,选手全部就位及开始
内部实现主要通过源码 中的 state 实现,volatile 关键字修饰(在线程切换时候,获取最新的数据)
翠花上代码

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

/**
 * 单例模式,发令枪测试单例创建
 * 1、修改发令枪数量
 * 2、修改doWork 方法内容即可使用
 * @author sloar,  [email protected]
 * @create 2019/9/16 18:11
 **/
public class CountDownLatchTest {

    // TODO 发令枪数量设置
    private static final int N = 10;

    public static void main(String rgs[]) throws InterruptedException {
        //发令枪测试
        CountDownLatch doneSignal = new CountDownLatch(N);
        Executor service = Executors.newCachedThreadPool();
        for (int i = 0; i < N; ++i) // create and start threads
            service.execute(new WorkerRunnable(doneSignal, i));

        doneSignal.await();           // wait for all to finish


    }
}


class WorkerRunnable implements Runnable {
    private final CountDownLatch doneSignal;
    private final int i;
    WorkerRunnable(CountDownLatch doneSignal, int i) {
        this.doneSignal = doneSignal;
        this.i = i;
    }
    public void run() {
        doWork(i);
        doneSignal.countDown();
    }

    // TODO 其他业务测试在此方法内修改代码即可
    void doWork(int i) {
        System.out.println(i + "--->"+ Demo.getInstance());
    }
}

你可能感兴趣的:(工具,源码)