线程分析-同步代码块-共享资源-卖票问题不安全实例
package com.liujinghe.lianxi1.a_thread;
class SaleTicket implements Runnable{
//不同商家买票问题
//这个方法是不安全的,会有票卖不出去,也有票重复mai
private static int ticket = 100;//总票数
@Override
public void run() {
// TODO Auto-generated method stub
while(true) {
if(ticket>0) {
//如果票数大于0,就卖票
System.out.println(Thread.currentThread().getName()+":卖出去第"+ticket+"张票");
ticket--;
//每卖出一张票,让线程休眠一定时间
try {
Thread.sleep(200);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else {
//如果小于0,则票卖完了
System.out.println("票卖完了");
//退出循环
break;
}
}
}
}
public class Demo {
public static void main(String[] args) {
//创建多个线程
Thread thread1 = new Thread(new SaleTicket(),"天猫");
Thread thread2 = new Thread(new SaleTicket(),"淘宝");
Thread thread3 = new Thread(new SaleTicket(),"京东");
Thread thread4 = new Thread(new SaleTicket(),"拼多多");
//开启线程
thread1.start();
thread2.start();
thread3.start();
thread4.start();
}
}
运行截图