gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 05:25:56 24 4
gpt4 key购买 nike

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com