public class ThreadDemo05 { public static void main(String args[]) { // 四个售票点应该控制同一个资源 Demo d = new Demo() ; Thread t1 = new Thread(d) ; Thread t2 = new Thread(d) ; Thread t3 = new Thread(d) ; Thread t4 = new Thread(d) ; t1.start() ; t2.start() ; t3.start() ; t4.start() ; } } class Demo implements Runnable { private int ticket = 50 ; Object obj = new Object();//申请一个对象 public void run() { while(this.ticket>0) { synchronized(obj) { if(this.ticket > 0) { exe(Thread.currentThread().getName()); } } } } public void exe(String name){ try { Thread.sleep(40); System.out.println( name + " sail --" + ticket--); System.out.println( name); System.out.println( name); } catch (Exception e) { System.out.println("异常"); } } };