题目要求解决同步问题,用synchronized解决
可是synchronized放哪呢?
```public class TicketOffice implements Runnable{
private int count = 30;
private int no = 0;
private boolean flag = false;
public void run(){
while(true){
synchronized(this){
if(sale()==false)break;
}
}
}
public boolean sale(){
if(count==0){
return false;
}
try{
Thread.sleep(500);
}catch (InterruptedException e){
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"抢到第"+(++no)+"张票,剩余"+count--+"张");
if(Thread.currentThread().getName().equals("PFZ")){
return false;
}
return true;
}
}
public class Test {
public static void main(String[] args) {
TicketOffice r = new TicketOffice();
Thread Z3 = new Thread(r);
Z3.setName("Z3");
Thread L4 = new Thread(r);
L4.setName("L4");
Thread PFZ = new Thread(r);
PFZ.setName("PFZ");
Z3.start();
L4.start();
PFZ.start();
}
}