您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

为什么即使修改了锁变量,我也会得到一个无限的while循环?

为什么即使修改了锁变量,我也会得到一个无限的while循环?

您忘了声明guard为易失性布尔值。

如果您将字段声明省略为volatile,则不会告诉JVM该字段可以被多线程看到,例如您的示例。

在这种情况下,的值guard将被读取一次,并且将导致无限循环。它将针对以下内容进行优化(无打印):

if(!guard)
{
    while(true)
    {
    }
}

现在为什么要System.out.println改变这种行为?因为writes是同步的,这迫使线程不缓存读取。

这里粘贴了println一种PrintStream使用的方法代码System.out.println

public void println(String x) {
    synchronized (this) {
        print(x);
        newLine();
    }
}

write方法

private void write(String s) {
    try {
        synchronized (this) {
            ensureopen();
            textOut.write(s);
            textOut.flushBuffer();
            charOut.flushBuffer();
            if (autoFlush && (s.indexOf('\n') >= 0))
                out.flush();
        }
    }
    catch (InterruptedioException x) {
        Thread.currentThread().interrupt();
    }
    catch (IOException x) {
        trouble = true;
    }
}

注意同步。

其他 2022/1/1 18:14:57 有628人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶