Java,可见性和无限循环的发生 [英] Java, visibility and infinite loop occurrence

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

问题描述

我正在研究实践中的Java并发性,并解释了以下代码片段不好的原因:

I'm studying Java Concurrency in Practice and there it is explained why the following snippet of code is bad:

public class NoVisibility {
    private static boolean ready;
    private static int number;
    private static class ReaderThread extends Thread {

      public void run() {
      while (!ready) {
        Thread.yield();
        System.out.println(number);
      }
    }

    public static void main(String[] args) {
       new ReaderThread().start();
       number = 42;
       ready = true;
   }
}

此代码可能会打印0或永远循环。
虽然很容易理解为什么 NoVisibility 可以打印0而不是42(由于重新排序的问题),但是
我有点困惑关于无限循环。

This code may print 0 or loop forever. While it is easy to understand why NoVisibility could print 0 instead of 42 (due to re-ordering issue), I'm a little confused about the infinite loop.

在此代码中,可能发生无限循环的实际情况是什么?

What is a practical scenario where an infinite loop may occurr, in this code?

推荐答案

ready 设置为 true 时,循环停止。主线程将 ready 设置为 true 。但是由于 ready 字段不是可变的,因此循环线程可能继续看到缓存的值: false

The loop stops when ready is set to true. And ready is set to true by the main thread. But since the ready field is not volatile, the looping thread might continue to see a cached value: false.

volatile 关键字保证,所有读取volatile字段的线程实际上都会看到该字段中存储的最后一个值通过任何其他线程。没有 volatile ,您将无法获得此保证。

The volatile keyword guarantees that all the threads reading a volatile field will actually see the last value stored in this field by any other thread. Without volatile, you don't have this guarantee.

这篇关于Java,可见性和无限循环的发生的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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