并发
解决办法:队列 + 锁
线程不安全示例(操作同一个对象)
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;
}
}
}