1 //实现Runnable,编写购票线程 2 public class MyRunnable implements Runnable{ 3 private int i; 4 @Override 5 public void run() { 6 // TODO Auto-generated method stub 7 while(true) { 8 synchronized (this) { 9 if(i == 10) { 10 break; 11 } 12 try { 13 Thread.sleep(50); 14 } catch (InterruptedException e) { 15 // TODO Auto-generated catch block 16 e.printStackTrace(); 17 } 18 19 System.out.println(Thread.currentThread().getName()+"抢到第"+(i+1)+"张票,剩余"+(10-(i+1))+"张票"); 20 i++; 21 //限死黄牛党囤票 22 if("黄牛党".equals(Thread.currentThread().getName())) { 23 break; 24 } 25 } 26 } 27 } 28 }
1 //测试类 2 public class Test { 3 public static void main(String[] args) { 4 MyRunnable m = new MyRunnable(); 5 Thread thread1 = new Thread(m,"桃跑跑"); 6 Thread thread2 = new Thread(m,"张票票"); 7 Thread thread3 = new Thread(m,"黄牛党"); 8 thread3.start(); 9 thread1.start(); 10 thread2.start(); 11 } 12 }
运行结果: