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

相关推荐

评论
点赞
1
分享

创作者周榜

更多
牛客网
牛客企业服务