案例:售票员问题,一共一百张票,四个窗口同时进行售票
public class Lock extends Thread{
static int i=100;
private String name;
static Object object=new Object();
public Lock(){
}
public Lock(String name){
this.name=name;
}
@Override
public void run() {
while (true){
//使用synchronized上锁进行监视,避免异常出现重复票
synchronized (object){
if (i<1){
break;
}else {
System.out.println(this.name+"正在出售第"+i+"张票");
i--;
}
}
}
}
}
Lock lock=new Lock("窗口一");
Lock lock1=new Lock("窗口二");
Lock lock2=new Lock("窗口三");
Lock lock3=new Lock("窗口四");
lock.start();//开启线程
lock1.start();
lock2.start();
lock3.start();