手工创建一个线程池
手工创建一个线程池,执行callable任务
/** * @Information: * @Author: HeHaoYuan * @Date: Created at 13:48 on 2019/8/12 * @Package_Name: PACKAGE_NAME */ import java.util.concurrent.*; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; public class MyExecutorService implements Callable { int tick = 200; private Lock lock = new ReentrantLock(); @Override public String call() throws Exception { for (int i = 0; i < 200; i++) { lock.lock(); if (tick > 0) { TimeUnit.MILLISECONDS.sleep(20); System.out.println(Thread.currentThread().getName()+"票还剩下" + tick-- + "张"); lock.unlock(); } } 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(8,12, 2000,TimeUnit.MILLISECONDS, new LinkedBlockingDeque<>()); Future future = executorservice.submit(thread1); Future future2 = executorservice.submit(thread1); Future future3 = executorservice.submit(thread1); Future future4 = executorservice.submit(thread1); Future future5 = executorservice.submit(thread1); future.get(); future2.get(); future3.get(); future4.get(); future5.get(); //关闭线程池 executorservice.shutdown(); } }
执行结果: