package edu.wtbu;标签:Thread,安全,void,start,案例,buyTicket,new,public From: https://www.cnblogs.com/123456dh/p/17229739.html
//不安全的买票
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--);
}
}