并发(不安全示例)
作者:互联网
并发
解决办法:队列 + 锁
线程不安全示例(操作同一个对象)
public static void main(String[] args) {
BuyTicket buyTicket = new BuyTicket();
// BuyTicket buyTicket1 = new BuyTicket();
// BuyTicket buyTicket2 = new BuyTicket();
new Thread(buyTicket,"张三").start();
new Thread(buyTicket,"李四").start();
new Thread(buyTicket,"王五").start();
}
/* 买票 */
static class BuyTicket implements Runnable{
int ticket = 20;
boolean flag = false;
@Override
public void run() {
while(!flag){
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
buy();
}
}
private void buy(){
System.out.println(Thread.currentThread().getName()+"买到了:"+ticket--);
if(ticket <= 0){
flag = true;
}
}
}
标签:Thread,安全,void,示例,并发,BuyTicket,new,start,buyTicket 来源: https://www.cnblogs.com/xy20211005/p/15669581.html