多个线程同时操作一个资源情况下,线程不安全,数据紊乱
//火车票抢票,模拟多个线程操作同一个对象
public class TicketThread implements Runnable{
private int ticketNum = 10;
@Override
public void run() {
while (true){
if (ticketNum<=0){
break;
}
System.out.println(Thread.currentThread().getName()+"抢到了第"+ticketNum--+"张票");
try {
Thread.sleep(200);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
public static void main(String[] args) {
TicketThread ticketObj = new TicketThread();
new Thread(ticketObj,"小明").start();
new Thread(ticketObj,"黄牛党").start();
new Thread(ticketObj,"谱乾兄").start();
}
}
扫描二维码,在手机上阅读!
评论