【0805作业】网络购票
1 package ticket; 2 3 public class Person implements Runnable { 4 private int count =10; 5 private int num = 0; 6 7 @Override 8 public void run() { 9 // TODO Auto-generated method stub 10 while (true) { 11 synchronized (this) { 12 if (count == 0) { 13 System.out.println("票已售罄!"); 14 break; 15 } 16 num++; 17 count--; 18 try { 19 Thread.sleep(10); 20 } catch (InterruptedException e) { 21 // TODO Auto-generated catch block 22 e.printStackTrace(); 23 } 24 System.out.println(Thread.currentThread().getName() + "抢到第" + num + "张票,剩余" + count + "张票。"); 25 26 27 } 28 } 29 } 30 }
1 package ticket; 2 3 public class Main { 4 public static void main(String[] args) { 5 Person p=new Person(); 6 Thread t1=new Thread(p,"桃跑跑"); 7 Thread t2=new Thread(p,"张票票"); 8 Thread t3=new Thread(p,"黄牛党"); 9 10 t1.start(); 11 t2.start(); 12 t3.start(); 13 } 14 }