Ohapi 2021-04-11 09:25 采纳率: 100%
浏览 140
已采纳

Java多线程入门——抢票问题

public class FinalAttack {
    public static void main(String[] args) {
        buyT station =new buyT();

        new Thread(station,"a").start();
        new Thread(station,"b").start();
        new Thread(station,"c").start();
    }
}
class buyT implements Runnable{

    private int tnum=10;
    boolean flag=true;
    @Override

    public void run() {
        while (flag){
            try {
                buy();
                //Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    private synchronized void buy() throws InterruptedException {
        if(tnum<=0){
            flag=false;
            return;
        }
        Thread.sleep(1000);
        System.out.println(Thread.currentThread().getName()+"拿到"+tnum--);

    }
}

上方代码运行结果为

我想实现的效果是模拟抢票:

为什么把sleep的位置换一下就可以实现了?

public class FinalAttack {
    public static void main(String[] args) {
        buyT station =new buyT();

        new Thread(station,"a").start();
        new Thread(station,"b").start();
        new Thread(station,"c").start();
    }
}
class buyT implements Runnable{

    private int tnum=10;
    boolean flag=true;
    @Override

    public void run() {
        while (flag){
            try {
                buy();
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    private synchronized void buy() throws InterruptedException {
        if(tnum<=0){
            flag=false;
            return;
        }
        System.out.println(Thread.currentThread().getName()+"拿到"+tnum--);

    }
}

希望能得到一个便于理解的回答,谢谢。

  • 写回答

3条回答 默认 最新

  • 关注

    sleep 放在同步函数没有意义,只是降低了程序的性能,因为同步函数当前线程没有运行完,别的线程是进不去的,而把sleep放在run里面,才能模拟抢票的情况。sleep的意思是当前线程休眠,休眠的时候,别的用户就可以同时进来抢票。

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因