WesenTCYS 2018-12-26 22:57 采纳率: 20%
浏览 690

求教synchronized在多线程的抢票运用有问题

题目要求解决同步问题,用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();


}

}

  • 写回答

1条回答 默认 最新

  • lhxinbobo 2018-12-27 03:55
    关注

    用synchronized 修饰sale()方法,同一时间只有一个线程能进入该方法。

    评论

报告相同问题?

悬赏问题

  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler