The need to manually lock and release.
Package com.LearnJava.Thread; Import java.util.concurrent.locks.ReentrantLock; / * sync block synchronized (sync monitor) { // requires synchronization code } synchronization monitor: lock commonly known, may be any instantiated The class share the same need but one example. * / class WindowSell the implements the Runnable { of ReentrantLock Lock = new new of ReentrantLock (); Private int Ticket = 100 ; @Override public void RUN () { the while ( to true ) { the try { Lock.lock () ; IF (ticket > 0) { System.out.println(Thread.currentThread().getName() + "sell " + ticket--); Thread.sleep(100); }else{ break; } } catch (InterruptedException e) { e.printStackTrace(); } finally { lock.unlock(); } } } } public class ThreadTestTicket { public static void main(String[] args) { WindowSell win = new WindowSell(); Thread t1 = new Thread(win); t1.setName("1号窗口"); Thread t2 = new Thread(win); t2.setName("2号窗口"); Thread t3 = new Thread(win); t3.setName("3号窗口"); t1.start(); t2.start(); t3.start(); } }