多线程售票
Posted wujf
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了多线程售票相关的知识,希望对你有一定的参考价值。
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(); } } } }
以上是关于多线程售票的主要内容,如果未能解决你的问题,请参考以下文章