while循环和线程的无限循环问题 [英] Infinite loop problem with while loop and threading

查看:309
本文介绍了while循环和线程的无限循环问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用一个基本示例来说明我的问题我有2个几乎相同的代码位。

Using a basic example to illustrate my problem I have 2 near-identical bits of code.

此代码导致循环无限运行。

This code causes the while loop to run infinitely.

private boolean loadAsset() {
    new Thread(new Runnable() {

        @Override
        public void run() {

            // Do something
            loaded = true;

        }
    }).start();

    while (!loaded) {
        // System.out.println("Not Loaded");
    }
    System.out.println("Loaded");
    return false;
}

然而,此代码(即在while循环中执行某些操作)会导致已加载要成功评估的变量,并允许 while 循环中断和方法完成。

This code however (i.e. doing something in the while loop) causes the loaded variable to be successfully evaluated and allows the while loop to break and method to finish.

private boolean loadAsset() {
    new Thread(new Runnable() {

        @Override
        public void run() {

            // Do something
            loaded = true;

        }
    }).start();

    while (!loaded) {
        System.out.println("Not Loaded");
    }
    System.out.println("Loaded");
    return false;
}

任何人都可以向我解释为什么会这样吗?

Can anyone explain to me why this is?

推荐答案

检查'loaded'是否明确声明为volatile。

Check that 'loaded' is definitely declared as volatile.

说明:如果变量是由多个线程读取和/或写入,然后您需要采取适当的线程安全措施。一种这样的线程安全措施是易失性的,它适用于原始值(或对象引用),它们被读取或写为简单动作,在给定的场合写入的值不依赖于先前的读取价值。有关更多信息,我在我的网站上有一篇关于易失性的文章(以及其他信息)一般来说,线程安全可能会有所帮助。

Explanation: if a variable is read and/or written by multiple threads, then you need to take appropriate thread-safety measures. One such thread-safety measure is volatile, which is suitable for primitive values (or object references) which are read or written as 'simple' actions with the value written on a given occasion not depending on the previously read value. For more information, I have an article about volatile on my web site (along with other information about thread-safety generally) that may be of help.

这篇关于while循环和线程的无限循环问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆