你以为的毫不费力,其实是竭尽全力。
继承Thread重写里面的run方法。
public class TicketDemo extends Thread{
private static int count = 20; //总票数
private static Object obj = new Object(); //定义一个静态对象
@Override
public void run() {
//死循环卖票
while(true){
//模拟 卖票耗时操作
try {
Thread.sleep(1000);//单位是毫秒值
//synchronized 操作 ,使用位置. 哪个地方出问题 ,就放到对应位置
synchronized (obj){
if(count>0){
System.out.println("当前卖出:"+count+"号票..");
count--; //每卖出1张 ,要减去1张
}else{
System.out.println("当前车次的票已售完...");
System.exit(0); //退出程序
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
//或者使用同步方法
/* public synchronized void show (String name){
}*/
public static void main(String[] args) {
TicketDemo td1 = new TicketDemo();
td1.start();
TicketDemo td2 = new TicketDemo();
td2.start();
}
}