-
public class WindowTestThree { public static void main(String[] args) { WindowThree w = new WindowThree(); Thread w1 = new Thread(w); Thread w2 = new Thread(w); Thread w3 = new Thread(w); w1.start(); w2.start(); w3.start(); } } class WindowThree implements Runnable { // private static int ticket = 100; private int ticket = 100; // final Object obj = new Object(); Object obj = new Object(); @Override public void run() { while (true) { synchronized (obj) { if (ticket > 0) { try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName() + ":成功售出一张票,剩余" + ticket + "张票"); ticket--; } else { break; } } } } }