1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
| class TicketWindow implements Runnable { private static int total_count = 100;
private final ReentrantLock lock = new ReentrantLock(true);
@Override public void run() { while (true) { if (total_count > 0) { try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } sale(); } else { break; } } System.out.println(Thread.currentThread().getName() + "的票已售空"); }
private void sale() { lock.lock(); try { if (total_count > 0) { System.out.println(Thread.currentThread().getName() + " 卖出第 " + (100 - total_count + 1) + " 张票"); total_count--; } } catch (Exception e) { e.printStackTrace(); } finally { lock.unlock(); } } }
public class SellTicketTest2 { public static void main(String[] args) { TicketWindow tw = new TicketWindow();
Thread t1 = new Thread(tw, "窗口1"); Thread t2 = new Thread(tw, "窗口2"); Thread t3 = new Thread(tw, "窗口3");
t1.start(); t2.start(); t3.start(); } }
|