Insufficiently Synchronized Java Code

本文深入探讨了在Java并发编程中,未充分同步共享变量可能导致的意外结果,通过具体实例展示了变量可见性和操作顺序的不确定性,强调了同步在并发编程中的关键作用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

I'm reading "Java Concurrency in Practice". Section 3.1.1 talks about it may cause surprising results when you do not provide enough synchronization to your shared variables.

Take a look at the example in the book:


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;
}
}


Explanations from the book:

NoVisibility could loop forever because the value of ready might never become visible to the reader thread. Even
more strangely, NoVisibility could print zero because the write to ready might be made visible to the reader thread
before the write to number, a phenomenon known as reordering. There is no guarantee that operations in one thread
will be performed in the order given by the program, as long as the reordering is not detectable from within that thread
even if the reordering is apparent to other threads. When the main thread writes first to number and then to done
without synchronization, the reader thread could see those writes happen in the opposite order or not at all.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值