如何在多线程环境中交换布尔值? [英] How to swap boolean value in multi-threaded environment?

查看:78
本文介绍了如何在多线程环境中交换布尔值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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屋!

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