无限循环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;

}

}

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?

解决方案

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.

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值