多线程写法,消除同步bug 糖不苦

public class Demo01 implements Runnable {
private int ticket = 10;

@Override
public void run() {
for (int i = 0; i < 10; i++) {
synchronized (this) {
if (ticket > 0) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()
+ ",正在卖出第" + (this.ticket--) + "张票!");

		}
	}
}

}
public static void main(String[] args) {
Demo01 mt = new Demo01();
new Thread(mt, "售票员A").start();
new Thread(mt, "售票员B").start();
new Thread(mt, "售票员C").start();
}

原文地址:https://www.cnblogs.com/wwyydd/p/14116989.html