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--);

    }
}

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

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

JAVA入门到精通:https://edu.csdn.net/course/detail/2981

您好,我是有问必答小助手,你的问题已经有小伙伴为您解答了问题,您看下是否解决了您的问题,可以追评进行沟通哦~

如果有您比较满意的答案 / 帮您提供解决思路的答案,可以点击【采纳】按钮,给回答的小伙伴一些鼓励哦~~

ps:问答VIP仅需29元,即可享受5次/月 有问必答服务,了解详情>>>https://vip.csdn.net/askvip?utm_source=1146287632