业务介绍:
多线程执行春节车票售卖!
代码逻辑如下:
/** * 售票任务 */ class TaskRunnable implements Runnable{ /** * 剩余车票数量 */ private AtomicInteger count; /** * 当前任务名称 */ private String taskName; /** * 任务锁 */ private ReentrantLock lock; public TaskRunnable(AtomicInteger count, String taskName, ReentrantLock lock) { this.count = count; this.taskName = taskName; this.lock = lock; } @Override public void run() { System.out.println(taskName + "号售票厅的开始售票~~"); while (true) { this.lock.lock(); if (this.count.get() <= 0) { //任务结束解锁 this.lock.unlock(); break; } System.out.println("恭喜抢到" + taskName+"号销售厅的车票! 当前剩余车票数" + this.count.decrementAndGet()); this.lock.unlock(); } System.out.println(taskName+"号售票厅的售票结束--"); } }
/** * @author Kevin * @DateTime 2019/1/12 11:08 * @Description */ public class ExecutorServiceL { public static void main(String[] args) { //创建线程池 ExecutorService executorService = getExecutor(); //执行任务 executeTask(executorService); while (true) { if (((ThreadPoolExecutor) executorService).getActiveCount() <= 0) { System.out.println("售票结束~~"); break; } } try { /** * 关闭线程池: * 1.不在接收新的任务 * 2.等待已执行任务执行完毕 * 3.关闭线程池(清除尚未执行任务,试图停止正在执行的任务) */ executorService.shutdown(); if (!executorService.awaitTermination(2, TimeUnit.SECONDS)) { System.out.println("尚未执行任务列表: "+executorService.shutdownNow()); } } catch (Exception e) { System.out.println("超出时间强制结束!"); } } /** * 执行任务 * * @param executorService */ public static void executeTask(ExecutorService executorService) { //总车票数 AtomicInteger total = new AtomicInteger(30); //线程锁 ReentrantLock lock = new ReentrantLock(); executorService.execute(new TaskRunnable(total, "1", lock)); executorService.execute(new TaskRunnable(total, "2", lock)); executorService.execute(new TaskRunnable(total, "3", lock)); executorService.execute(new TaskRunnable(total, "4", lock)); } /** * 获取线程池 * * @return */ public static ExecutorService getExecutor() { return new ThreadPoolExecutor( 2, 4, 2, TimeUnit.SECONDS, new SynchronousQueue(), new ThreadPoolExecutor.DiscardOldestPolicy() ); } }