`
leero
  • 浏览: 10677 次
  • 性别: Icon_minigender_1
  • 来自: 海口
社区版块
存档分类
最新评论

高手来回答下,这段程序的原理

阅读更多

public class Test {

    private  static boolean stopRequested;

 

    public static void main(String[] args) throws InterruptedException {

        Thread backgroundThread = new Thread(new Runnable() {

            public void run() {

                int i = 0;

                while (!stopRequested) {

                    i++;

//                    if(i %10000 == 0) System.out.println(" in thread");

                }

            }

        });

 

        backgroundThread.start();

        Thread.sleep(1000);

        stopRequested = true;

        System.out.println(stopRequested);

    }

}

 

这段代码,会一直运行下去。

 

如果把注释的那行打开,就是下面这样,程序一秒后就停止,大神分析下为什么?

public class Test {

    private  static boolean stopRequested;

 

    public static void main(String[] args) throws InterruptedException {

        Thread backgroundThread = new Thread(new Runnable() {

            public void run() {

                int i = 0;

                while (!stopRequested) {

                    i++;

                    if(i %10000 == 0) System.out.println(" in thread");

                }

            }

        });

 

        backgroundThread.start();

        Thread.sleep(1000);

        stopRequested = true;

        System.out.println(stopRequested);

    }

}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics