//实现Runnable接口 public class SellTicket implements Runnable {
private int count = 100; //重写run方法 @Override public void run() { while (true) { try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } //希望这是一个整体不要被其他线程干扰,使用线程同步代码块锁定 // alt+ctrl+t 可以选择各种包裹起来 synchronized (this) { if (count == 0) { break; } count--; System.out.println(Thread.currentThread().getName() + "卖出一张票,还剩下" + count + "张票"); } } } //定义一个测试类:
public class Test { public static void main(String[] args) { SellTicket s = new SellTicket(); new Thread(s,"窗口1").start(); new Thread(s,"窗口2").start(); new Thread(s,"窗口3").start(); } }