首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >通过不同的方法更改runnable中的AtomicBoolean值

通过不同的方法更改runnable中的AtomicBoolean值
EN

Stack Overflow用户
提问于 2019-10-30 05:28:37
回答 1查看 454关注 0票数 1

MyRunnable有一个原子布尔值,一个方法需要将其设置为true,另一个方法需要在多线程环境中设置为false

代码语言:javascript
复制
   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循环将旋转,直到原子布尔值设置为true

代码语言:javascript
复制
public void setToFalse() {
        ExecutorService executorService =  Executors.newFixedThreadPool(4);
        AtomicBoolean atomicBoolean = new AtomicBoolean(false);
        executorService.submit(new RunnableStudentFuture(atomicBoolean));
    }

寻找像setToTrue这样的方法从while循环中走出来。信号之类的东西

代码语言:javascript
复制
public void setToTrue() {

    }

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

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

EN

回答 1

Stack Overflow用户

发布于 2019-10-30 10:10:12

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

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

在下面的示例中,我向MyRunnable添加了一些方法来设置该值。

代码语言:javascript
复制
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方法,您需要具有对另一个线程中的实例的引用。因此,为了说明:

代码语言:javascript
复制
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(); 
}

此方法将在另一个线程中执行runnable,然后在原始线程中过一段时间后调用setToTrue。您将看到如下所示的输出:

代码语言:javascript
复制
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
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58615682

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档