1. 程式人生 > >基於執行緒池的多執行緒售票demo

基於執行緒池的多執行緒售票demo

廢話不多說,直接就開擼

import org.springframework.util.StopWatch;

import java.util.concurrent.*;

/**
 *   基於執行緒池實現的多執行緒賣票demo
 *   joey li
 *   2018-4-12
 *   qq: 1914295136
 */
public class TicketRunnable implements Runnable {
    private CountDownLatch count;
    private CyclicBarrier barrier;

    public TicketRunnable(CountDownLatch count,CyclicBarrier barrier) {
        this.count = count;
        this.barrier = barrier;
    }

    private int num = 10000;  // 總票數
    Object lock = new Object();

    public void sellTicket() {
        synchronized (lock) {
            if (num > 0) {
                System.out.print(Thread.currentThread().getName() + "售出票號" + num);
                num--;
                if(num!=0)
                    System.out.println(",還剩" + num + "張票--" );
                else
                    System.out.println(",票已經票完!--");
            }
        }
        try {
            Thread.sleep(10);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName()+"到達,等待中...");
        try{
            barrier.await();    // 此處阻塞  等所有執行緒都到位後一起進行搶票
            if(Thread.currentThread().getName().equals("pool-1-thread-1")){
                System.out.println("---------------全部執行緒準備就緒,開始搶票----------------");
            }else {
                Thread.sleep(10);
            }
        }catch (Exception e){}
        while (num > 0) {
            sellTicket();
        }
        count.countDown();  //當前執行緒結束後,計數器-1
    }

    /**
     *
     * @param args
     */
    public static void main(String[] args) {
        int threadNum = 100;    //模擬多個視窗 進行售票
        final CyclicBarrier barrier = new CyclicBarrier(threadNum);
        final CountDownLatch count = new CountDownLatch(threadNum);  // 用於統計 執行時長
        StopWatch watch = new StopWatch();
        watch.start();
        TicketRunnable tickets = new TicketRunnable(count,barrier);
        ExecutorService executorService = Executors.newFixedThreadPool(threadNum);
        //ExecutorService executorService = Executors.newCachedThreadPool();
        for (int i = 0; i < threadNum; i++) {   //此處 設定數值  受限於 執行緒池中的數量
            executorService.submit(tickets);
        }
        try {
            count.await();
            executorService.shutdown();
            watch.stop();
            System.out.println("耗 時:" + watch.getTotalTimeSeconds() + "秒");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
原文地址:http://www.cnblogs.com/xifenglou/p/8807323.html