三大线程不安全案例之一(买票案例)

package cn.ruhsang.syn;

//不安全的买票
//线程不安全,有负数
public class UnsafeBuyTicket {
public static void main(String[] args) {
BuyTicket station = new BuyTicket();

new Thread(station,"苦逼的我").start();
new Thread(station,"牛逼的你们").start();
new Thread(station,"可恶的黄牛党").start();
}

}
class BuyTicket implements Runnable{

//
private int ticketNums = 10;
boolean flag = true;//外部停止方式

@Override
public void run() {
//买票
while (flag){
buy();
}

}
private void buy(){
//判断是否有票
if(ticketNums<=0){
flag = false;
return;
}
//模拟延时
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//买票
System.out.println(Thread.currentThread().getName()+"拿到"+ticketNums--);
}
}
package cn.ruhsang.syn;

//不安全的买票
//线程不安全,有负数
public class UnsafeBuyTicket {
public static void main(String[] args) {
BuyTicket station = new BuyTicket();

new Thread(station,"苦逼的我").start();
new Thread(station,"牛逼的你们").start();
new Thread(station,"可恶的黄牛党").start();
}

}
class BuyTicket implements Runnable{

//
private int ticketNums = 10;
boolean flag = true;//外部停止方式

@Override
public void run() {
//买票
while (flag){
buy();
}

}
private void buy(){
//判断是否有票
if(ticketNums<=0){
flag = false;
return;
}
//模拟延时
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//买票
System.out.println(Thread.currentThread().getName()+"拿到"+ticketNums--);
}
}
posted @ 2021-06-07 18:22  逆骨111  阅读(57)  评论(0)    收藏  举报