1 package testBlog; 2 3 class MyThread implements Runnable { 4 private int ticket = 5; 5 6 @Override 7 public void run() { 8 int x; 9 for (x = 0; x < 20; x++) { 10 synchronized (this) {// 同步块 11 if (ticket > 0) { 12 try { 13 Thread.sleep(100);// 休眠1s,模拟延迟 14 } catch (InterruptedException e) { 15 e.printStackTrace(); 16 } 17 System.out.println(Thread.currentThread().getName() + "卖票,票数剩余:" + ticket--);// 票数记得要"后--" 18 } 19 } // 同步块到此结束.同步块中包括:判断是否有票,和卖票两个操作 20 } 21 } 22 23 } 24 25 public class Test { 26 public static void main(String[] args) { 27 MyThread mt = new MyThread(); 28 new Thread(mt, "票贩子A").start(); 29 new Thread(mt, "票贩子B").start(); 30 new Thread(mt, "票贩子C").start(); 31 32 } 33 }