java线程遇到的小问题

为什么下面的代码在main的方法中加上 System.out.println("main"+i); 子线程才会正常执行,

如果不加,子线程没有任何输出?

自己尝试让主线程 sleep 又可以正常输出,求大佬解惑

public class TestStop implements Runnable{
    private boolean flag = true;

    @Override
    public void run() {
        int i= 1000;
        while (i > 0) {
            System.out.println(flag);
            System.out.println("run"+i--);
        }

    }
    public void stop(){
        this.flag = false;
    }

    public static void main(String[] args) throws InterruptedException {
        TestStop testStop = new TestStop();

        new Thread(testStop).start();

        for (int i = 0; i < 100000; i++) {
//            System.out.println("main"+i);
            if (i==900) {
                //切换标志位让线程停止
                testStop.stop();
                System.out.println("线程停止");
            }
        }
    }
}
#java多线程##申通快递#
全部评论
是不是你不加for循环里的输出,for循环执行得太快,子线程的结果还没有来得及print输出,main线程就已经结束返回了(因为print输出操作其实是比较耗时的),for循环里加了输出之后,100000次输出每次都要打印输出,子线程肯定已经有print了
点赞 回复 分享
发布于 2020-04-27 00:37

相关推荐

frutiger:逆天,我家就安阳的,这hr咋能说3k的,你送外卖不比这工资高得多?还说大厂来的6k,打发叫花子的呢?这hr是怎么做到说昧良心的话的
找工作时遇到的神仙HR
点赞 评论 收藏
分享
评论
点赞
1
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务