首页 > 其他分享 >不安全案例

不安全案例

时间:2023-03-18 12:56:59浏览次数:31  
标签:Thread 安全 void start 案例 buyTicket new public

package edu.wtbu;
//不安全的买票
public class Demo08 {
public static void main(String[] args) {
buyTicket buyTicket = new buyTicket();

new Thread(buyTicket,"我").start();
new Thread(buyTicket,"你").start();
new Thread(buyTicket,"黄牛党").start();
}
}
class buyTicket implements Runnable{
private int ticketNums=10;//票
boolean flag=true;//外部停止方式
@Override
public void run() {
//买票
while (flag){
try {
buy();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}

public void buy() throws InterruptedException {
//判断是否有票
if(ticketNums<=0){
flag=false;
return;
}
//模拟延时
Thread.sleep(1000);
//买票
System.out.println(Thread.currentThread().getName()+"拿到了"+ticketNums--);
}
}

标签:Thread,安全,void,start,案例,buyTicket,new,public
From: https://www.cnblogs.com/123456dh/p/17229739.html

相关文章