package day_24多线程;
public class 多线程的安全_卖火车票 {
public static void main(String[] args) {
new Ticket().start();
new Ticket().start();
new Ticket().start();
new Ticket().start();
}
}
class Ticket extends Thread {
private static int ticket = 100;// 100张火车票4个窗口买 static设置车票是共有的
private static Object obj=new Object();//有4个new thread 必须是加static 使得object是唯一的
public void run() {
while (true) {
synchronized (Ticket.class) {//同步代码块的对象选择 必须是唯一的
if (ticket == 0) {
break;
}
try {
Thread.sleep(10); //睡眠线程1,2,3,4 线程安全问题
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(getName() + "这是第" + ticket-- + "张多车票");
}
}
}
}