买票问题-线程的同步
1 //买票问题 2 package ThreadL; 3 4 public class Thread9 { 5 public static void main(String[] args){ 6 Thread th1 = new Thread(new Thread9L(),"AAA"); 7 Thread th2 = new Thread(new Thread9L(),"BBBBBB"); 8 th1.start(); 9 th2.start(); 10 } 11 } 12 class Thread9L implements Runnable{ 13 static int ticket = 100; 14 static int count = 0; 15 public void run(){ 16 while(true){ 17 synchronized("L") //动作原语 18 { 19 if(ticket>0){ 20 /* try { 21 Thread.sleep(1000); 22 } catch (InterruptedException e) { 23 // TODO Auto-generated catch block 24 e.printStackTrace(); 25 } 26 */ System.out.println(Thread.currentThread().getName() + "\t出售第\t" + ticket-- + "\t张车票。"); 27 count++; 28 }else{ 29 System.out.println(Thread.currentThread().getName() + "\t已售完。\t" + count); 30 break; 31 } 32 } 33 } 34 } 35 }