1. 程式人生 > >多執行緒售票示例

多執行緒售票示例

業務介紹:

  多執行緒執行春節車票售賣!

程式碼邏輯如下:

/**
 * 售票任務
 */
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() ); } }
售票入口