JAVA多线程实现多个线程同时运行

package concurrent;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Auth: zhouhongliang
 * Date:2019/8/1
 * 多个线同时运行
 * CyclicBarrier
 */
public class CyclicBarrierDemo {
    private static CyclicBarrier cyclicBarrier = new CyclicBarrier(5);

    public static void main(String[] args) {
        ExecutorService executorService = Executors.newCachedThreadPool();
        for (int i=0;i<10;i++){
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            executorService.execute(()->{
                try {
                    play();
                } catch (BrokenBarrierException e) {
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
        }
    }

    public static void play() throws BrokenBarrierException, InterruptedException {
        System.out.println(Thread.currentThread().getName() + " 已准备");
        cyclicBarrier.await();
        System.out.println(Thread.currentThread().getName() + " 开始执行");
    }
}

输出结果:
pool-1-thread-1 已准备
pool-1-thread-2 已准备
pool-1-thread-3 已准备
pool-1-thread-4 已准备
pool-1-thread-5 已准备
pool-1-thread-5 开始执行
pool-1-thread-1 开始执行
pool-1-thread-2 开始执行
pool-1-thread-4 开始执行
pool-1-thread-3 开始执行
pool-1-thread-3 已准备
pool-1-thread-5 已准备
pool-1-thread-1 已准备
pool-1-thread-4 已准备
pool-1-thread-2 已准备
pool-1-thread-2 开始执行
pool-1-thread-1 开始执行
pool-1-thread-4 开始执行
pool-1-thread-5 开始执行
pool-1-thread-3 开始执行

Process finished with exit code 0

    原文作者:bpxl82438
    原文地址: https://blog.csdn.net/bpxl82438/article/details/100951346
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞