码迷,mamicode.com
首页 > 编程语言 > 详细

多线程售票

时间:2018-05-25 21:07:59      阅读:227      评论:0      收藏:0      [点我收藏+]

标签:对象   cep   import   tran   窗口   private   class   break   stat   

package threadT;

public class ThreadMain {
    public static void main(String args[]) {
        SellTicket str = new SellTicket(10);
        Thread tr1 = new Thread(str, "窗口1");
        Thread tr2 = new Thread(str, "窗口2");
        Thread tr3 = new Thread(str, "窗口3");
        tr1.start();
        tr2.start();
        tr3.start();
    }
}
package threadT;

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

public class SellTicket implements Runnable {

    // 定义票的数量
    private int tickets = 0;

    public SellTicket(int count) {
        tickets = count;
    }

    // 定义锁对象
    private final Lock lock = new ReentrantLock();

    public void run() {
        // 卖完标记
        boolean over = false;
        while (true) {
            try {
                if (tickets == 0) {
                    System.out.println(Thread.currentThread().getName() + "检测到已售完");
                    over = true;
                    break;
                }
                // 加锁
                lock.lock();
                if (tickets > 0) {
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName() + "正在出售第" + (tickets--) + "张票");
                }
            } finally {
                if (!over)
                    // 释放锁
                    lock.unlock();
            }
        }
    }

}

 

多线程售票

标签:对象   cep   import   tran   窗口   private   class   break   stat   

原文地址:https://www.cnblogs.com/wujf/p/9090124.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!