package cn.mldn.demo;
class MyThread implements Runnable{
private int tickets = 5;
@Override
public void run() {
for (int i = 0; i < 20 ; i++) {
if (this.tickets > 0) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "sell,tickets = " + this.tickets-- );
}
}
}
}
public class TestDemo{
public static void main(String[] args ) throws Exception{
MyThread mt = new MyThread();
new Thread(mt , "sellsA").start();
new Thread(mt , "sellsB").start();
new Thread(mt , "sellsC").start();
new Thread(mt , "sellsD").start();
}
}
/*
sellsBsell,tickets = 4
sellsDsell,tickets = 2
sellsCsell,tickets = 3
sellsAsell,tickets = 5
sellsDsell,tickets = 1
sellsCsell,tickets = -1
sellsAsell,tickets = -2
sellsBsell,tickets = 0
*/
/*如果未进行同步,在多线程且有延迟休眠的情况下,剩余票数未1时,第一个抢占的线程将不会修改剩余数,
而是直接进行休眠,第二、第三等线程也会依次抢占资源,后进入休眠,最后统一进入run()方法,故出现以上
卖出负数票的错误
*/
转载于:https://my.oschina.net/u/2916018/blog/850011