手工创建一个线程池

白昼怎懂夜的黑 提交于 2019-11-28 04:02:14

手工创建一个线程池,执行callable任务

 

/**
 * @Information:
 * @Author: HeHaoYuan
 * @Date: Created at 13:48 on 2019/8/12
 * @Package_Name: PACKAGE_NAME
 */
import java.util.concurrent.*;

public class MyExecutorService implements Callable {
    int tick = 20;

    @Override
    public String call() throws Exception {
        for (int i = 0; i < 20; i++) {
            if (tick > 0) {
                System.out.println(Thread.currentThread().getName()+"票还剩下" + tick-- + "张");
            }
        }
        return "票已经卖完";
    }
}
class ExecutorTest {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        MyExecutorService thread1 = new MyExecutorService();

        /**

         * 核心线程池的大小是:3

         * 线程池的最大数量:5

         * 空闲线程的存活时间:2000

         * 空闲线程的存活时间的单位:ms

         * 工作队列:基于链表结构的阻塞队列

         * 饱和策略:没有声明默认采用AbortPolicy (无法处理新任务抛出异常)

         */
        ExecutorService executorservice =
                new ThreadPoolExecutor(3,3,
                        2000,TimeUnit.MILLISECONDS,
                        new LinkedBlockingDeque<>());

        Future future = executorservice.submit(thread1);
        Future future2 = executorservice.submit(thread1);
        Future future3 = executorservice.submit(thread1);
        future.get();
        future2.get();
        future3.get();

        //关闭线程池
        executorservice.shutdown();
    }
}

最大任务执行个数等于核心线程池的大小

 

 

import java.util.concurrent.*;public class MyExecutorService implements Callable {int tick = 20;    @Overridepublic String call() throws Exception {for (int i = 0; i < 20; i++) {if (tick > 0) {System.out.println(Thread.currentThread().getName()+"票还剩下" + tick-- + "张");            }        }return "票已经卖完";    }}class ExecutorTest {public static void main(String[] args) throws ExecutionException, InterruptedException {MyExecutorService thread1 = new MyExecutorService();        ExecutorService executorservice =                new ThreadPoolExecutor(3,5,                        2000,TimeUnit.MILLISECONDS,                        new LinkedBlockingDeque<>());        Future future = executorservice.submit(thread1);        Future future2 = executorservice.submit(thread1);        Future future3 = executorservice.submit(thread1);        future.get();        future2.get();        future3.get();        //关闭线程池executorservice.shutdown();    }}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!