多線程賣票:使用Lock鎖

package com.xjh.demo.thread;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class SellTicket implements Runnable{

    private int total=100;

    private Lock lock=new ReentrantLock();

    @Override
    public void run() {
        while (true){
            try{
                lock.lock();
                if(total>0){
                    try {
                        Thread.sleep(100);
                    }catch (Exception e){

                    }
                    System.out.println(Thread.currentThread().getName()+"正在賣第"+(total--)+"張票");
                }
            }finally {
                lock.unlock();
            }

        }
    }
}

 

package com.xjh.demo.thread;

public class SellTicketDemo {
    public static void main(String[] args) {
        SellTicket sellTicket = new SellTicket();
        new Thread(sellTicket, "窗口1").start();
        new Thread(sellTicket, "窗口2").start();
        new Thread(sellTicket, "窗口3").start();
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章