为什么这个Java类不是线程安全的.
Why is this java class not Thread safe.
class TestClass { private int x; int get() { return x; } void set(int x) { this.x = x; } }
我读到需要使用 synchronized
关键字来使其线程安全吗?毕竟这些操作不是在原子内部完成的吗?
I read that keyword synchronized
is needed to make it thread safe? After all isn't the operations done inside atomic?
尽管赋值本身是一个原子操作,但由于硬件和编译器的实现不同,不同的线程可能会看到成员x的不同值.即,由于某种缓存,一个线程进行的修改可能对另一个线程不可见.这通常称为线程可见性问题.
Although the assignment itself is an atomic operation, due to different hardware and compiler implementations, different threads may see different values of the member x. I.e., a modification by one thread may be invisible to the other thread, because of some kind of caching. This is usually called a thread visibility problem.
您可以通过在监视器上进行同步(使用synced关键字或java.util.concurrent锁),或将x声明为易失性来正确同步代码.
You can synchronize your code properly either by synchronizing on a monitor (using the synchronized keyword or the java.util.concurrent locks), or by declaring x to be volatile.
这篇关于Java类中的线程安全的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程技术网(www.editcode.net)!