java - 通过不同的方法更改可运行对象中的 AtomicBoolean 值

标签 java concurrency completable-future

MyRunnable 有一个原子 boolean 值,需要通过一种方法将其设置为 true, 另一种在多线程环境中设置为 false 的方法

   private final class MyRunnable<V> implements Runnable {

    private  AtomicBoolean atomicBoolean;

    public RunnableStudentFuture(AtomicBoolean atomicBoolean) {
        this.atomicBoolean = atomicBoolean;
    }

    @Override
    public void run() {

        while (!atomicBoolean.get()) {
            //spin
        }
    }
}

当我执行此方法时,runnable 中的 while 循环将旋转,直到原子 boolean 值设置为 true

public void setToFalse() {
        ExecutorService executorService =  Executors.newFixedThreadPool(4);
        AtomicBoolean atomicBoolean = new AtomicBoolean(false);
        executorService.submit(new RunnableStudentFuture(atomicBoolean));
    }

寻找像 setToTrue 这样的方法来退出 while 循环。 类似信号的东西

public void setToTrue() {

    }

如何在多线程环境中实现这一目标?

是否可以使用CompletableFuture来实现这一点

最佳答案

要记住的重要一点是,您将需要能够(以某种方式)从您希望从中设置其值的任何线程引用atomicBoolean。由于这是 Runnable 中的私有(private)成员,这意味着您必须:

  1. 在该可运行对象上公开一个方法来设置值;和
  2. 保留该可运行实例的引用。

在下面的示例中,我向 MyRunnable 添加了方法以启用设置值。

public class MyRunnable implements Runnable {
    private final AtomicBoolean atomicBoolean = new AtomicBoolean();

    public void setToFalse() {
        this.atomicBoolean.set(false);
    }

    public void setToTrue() {
        this.atomicBoolean.set(true);
    }

    @Override
    public void run() {
        this.setToFalse();
        while (!atomicBoolean.get()) {
            System.out.println("running like mad");
            try {Thread.sleep(150L);} catch (Exception e) {}
        }
    }
}

要调用 setToTrue 方法,您需要在另一个线程中拥有可供该实例使用的引用。举例说明:

public static void main(String... none) throws Exception {
    MyRunnable myRunnable = new MyRunnable();

    System.out.println("starting runnable on different thread");
    ExecutorService executorService = Executors.newFixedThreadPool(4);
    executorService.execute(myRunnable);

    System.out.println("wait on main thread");
    try {Thread.sleep(1000L);} catch (Exception e) {}

    System.out.println("calling set to true on main thread");
    myRunnable.setToTrue(); 
}

此方法将在另一个线程中执行可运行对象,然后在一段时间后在原始线程中调用 setToTrue 。您将看到如下输出:

starting runnable on different thread
wait on main thread
running like mad
running like mad
running like mad
running like mad
running like mad
running like mad
running like mad
calling set to true on main thread

关于java - 通过不同的方法更改可运行对象中的 AtomicBoolean 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58615682/

相关文章:

java - JPA 查询验证日期以及自该日期以来的天数是否> 50

go - 关闭具有循环依赖性的 channel

java - 在 Java 中从 C++ 复制延迟/异步启动策略

java - CompletableFuture : proper way to run a list of futures, 等待结果并处理异常

java - API 调用返回 Null

java - collections.shuffle 中的默认随机源

无互斥

java - `thenRunAsync(...)` 和 `CompletableFuture.runAsync(() -> { ... });` 有关联吗?

java - Mysql表中的URL可以是超链接吗?

java - 为什么创建了一个JFrame对象并设置为可见后,程序还没有结束执行?