如何在多线程环境中交换布尔值? [英] How to swap boolean value in multi-threaded environment?
问题描述
1.
volatile boolean bool = false;
// ...
bool = !bool;
2.
volatile AtomicBoolean bool= new AtomicBoolean(false);
// ...
bool.set(!bool.get());
如果有多个线程正在运行,并且其中一个需要交换bool
的值并使新值对于其他线程可见,那么这两种方法是否存在相同的问题,即允许在另一个线程中进行操作-在读写之间,还是AtomicBoolean
是否确保在.get()
和.set()
的调用之间什么都不会发生?
If there are multiple threads running, and one of them needs to swap the value of bool
and making the new value visible for other threads, do these 2 approaches have the same problem of allowing for another thread's operation to happen in-between the read and write, or does AtomicBoolean
assure that nothing will happen in-between the call to .get()
and .set()
?
推荐答案
AtomicBoolean
无法保证get()
和set()
之间不会发生任何事情.
您可以创建在同一个对象上同步的3个方法get()
,set()
和swap()
.
AtomicBoolean
cannot assure nothing will happen between the get()
and set()
.
You could create 3 methods get()
, set()
and swap()
that synchronize on the same object.
您可以尝试这样的事情:
You could try something like this:
public class SyncBoolean
{
public SyncBoolean()
{
value = false;
}
public synchronized boolean get()
{
return (value);
}
public synchronized void set(boolean newValue)
{
value = newValue;
}
public synchronized void swap()
{
value = !value;
}
private boolean value;
} // class SyncBoolean
这篇关于如何在多线程环境中交换布尔值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!