0.9.2、自定义线程池结合CyclicBarrier

描述

使用自定义线程池,模拟三个人上车

自定义线程池

线程池作为工具类使用
自定义线程池

CyclicBarrier 的单独使用

单独使用 CyclicBarrier
多线程学习——栅栏的一个实现 CyclicBarrier

Java
import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.google.common.util.concurrent.ThreadFactoryBuilder;

import java.util.Collections;
import java.util.List;
import java.util.concurrent.*;

/**
 * @Title: 线程池测试
 * @Description: 线程池测试
 * @Author: wujie
 * @Version: v1.0
 * @Date:2020-06-10
 * @Updatedby:
 */
public class ThreadTest {
    private final static int CORE_POOL_SIZE = 10;
    private final static int MAX_I_MUM_POOL_SIZE = 10;
    private final static long KEEP_ALIVE_TIME = 0L;
    private final static int WORKQUEUE_SIZE = 1024;
    /**
     * 自定义线程名称,方便的出错的时候溯源
     */
    private static ThreadFactory namedThreadFactory = new ThreadFactoryBuilder().setNameFormat("center-pool-%d").build();
    private static ExecutorService threadPool = new ThreadPoolExecutor(CORE_POOL_SIZE, MAX_I_MUM_POOL_SIZE, KEEP_ALIVE_TIME,
            TimeUnit.MILLISECONDS, new LinkedBlockingDeque(WORKQUEUE_SIZE), namedThreadFactory, new ThreadPoolExecutor.AbortPolicy());

    /**
     * 获取线程池
     */
    public static ExecutorService getThreadPool() {
        return threadPool;
    }

    /**
     * 获取线程池工厂
     */
    public static ThreadFactory getThreadFactory(){
        return namedThreadFactory;
    }

    /**
     * 执行任务
     * @param r
     */
    public static void newTask(Runnable r) {
        threadPool.execute(r);
    }

    /**
     * 关闭线程池(如有在执行任务则等待)
     */
    public static void destroyExecutorService(){
        System.out.println("关闭线程池");
        if(!threadPool.isShutdown()){
            threadPool.shutdown();
        }
    }

    /**
     * 立即关闭线程池
     */
    public static void destroyNowExecutorService(){
        System.out.println("立即关闭线程池");
        if(!threadPool.isShutdown()){
            threadPool.shutdownNow();
        }
    }

    /**
     * 线程池是否关闭
     * @return
     */
    public static boolean isExecutorServiceDownNow(){
        return threadPool.isShutdown();
    }



    public static void main(String[] args)  {

        final List list = Collections.synchronizedList(Lists.newArrayList());

        Callable callable = new Callable() {
            @Override
            public Object call() throws Exception {
                System.out.println("驾驶员 "+Thread.currentThread().getName() + " 出发");
                return list;
            }
        };
        //将 callable 传入到 FutureTask 构造函数
        FutureTask futureTask = new FutureTask(callable);
        CyclicBarrier c = new CyclicBarrier(1, namedThreadFactory.newThread((futureTask)));

        newTask(namedThreadFactory.newThread(new MyThread(c,list)));
        newTask(namedThreadFactory.newThread(new MyThread(c,list)));
        newTask(namedThreadFactory.newThread(new MyThread(c,list)));

        //获取结果-这里注意时间
        List listResult = null;
        try {
            listResult = (List) futureTask.get(2, TimeUnit.MINUTES);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        }finally {
            futureTask.cancel(true);
        }

        System.out.println(System.currentTimeMillis() + ":满员喽,都坐稳当了,本次列车出发咯");
        System.out.println("收到的门票:"+JSON.toJSONString(listResult));
        destroyExecutorService();
        System.out.println("线程池是否关闭"+isExecutorServiceDownNow());

    }

    public static class MyThread extends Thread {
        private CyclicBarrier c;
        private List list;

        public MyThread(CyclicBarrier c,List list) {
            this.c = c;
            this.list = list;
        }

        public void run() {
            try {
                Thread.currentThread().sleep(120);
                list.add("门票"+System.currentTimeMillis()+"元");
                System.out.println("乘客 " + Thread.currentThread().getName() + " 坐好了");
                c.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (BrokenBarrierException e) {
                e.printStackTrace();
            }

        }
    }
}
运行结果
乘客 center-pool-2 坐好了
乘客 center-pool-4 坐好了
乘客 center-pool-6 坐好了
驾驶员 center-pool-2 出发
1591780796401:满员喽,都坐稳当了,本次列车出发咯
收到的门票:["门票1591780796400元","门票1591780796400元","门票1591780796400元"]
关闭线程池
线程池是否关闭true

Process finished with exit code 0

参考资料

[1]、https://blog.csdn.net/bestcxx/article/details/107436945

已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 数字20 设计师:CSDN官方博客 返回首页