java - 如何在 Executor 中调度 Callable

标签 java executorservice

我正在尝试安排一个等待某些条件发生的线程。如果条件为真,则返回一些结果,否则再次安排自身在延迟一段时间后执行。为了实现这一点,我使用 Executors安排Callable<Boolean>但第二次重新安排后它挂起。

 final ExecutorService executor = Executors.newFixedThreadPool(2);
    final MutableBoolean status = new MutableBoolean(false);

    new Thread(new Runnable() {
        @Override
        public void run() {
            System.out.println("Waiting now to set status");
            try {
                Thread.sleep(5*1000);
                System.out.println("status is now true");
                status.setValue(true);
            } catch (InterruptedException e) {
            }

        }
    }).start();

    Future<Boolean> future = executor.submit(new Callable<Boolean>() {
        public int count=0;
        @Override
        public Boolean call() throws Exception {
            if(status.isTrue()){
                System.out.println("Condition has become true now");
                return status.booleanValue();
            } else {
                System.out.println("Not true yet, count" + count++ + " Rescheduling");
                Future<Boolean> future = executor.submit(this);
                return future.get();
            }
        }
    });

    boolean finalStatus = future.get();
    System.out.println("Final status" + finalStatus);

输出:

Waiting now to set status
Not true yet, count0 Rescheduling
Not true yet, count1 Rescheduling
status is now true

对于可能出现的问题有什么建议吗?

谢谢

最佳答案

您创建了一个大小为 2 的线程池。然后,您从池中运行的作业(递归地)向该池提交任务,并等待这些任务完成(调用 future.get())。

关于java - 如何在 Executor 中调度 Callable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24005008/

相关文章:

Java + Eclipse : False possible null pointer dereference?

Java-单击按钮时更改标签文本

java - 在 hibernate 中映射引用项目中的类

java - 我应该如何在 Java 中指定亚洲字符和字符串常量?

java - 优雅地为 ExecutorServices 实现队列长度指示器

java - Executor ScheduledThreadPool "more"线程池有什么作用?

使用 Executor 的 JavaFX 应用程序在退出时挂起

java - 为什么 Spring Boot 中使用 ExecutorCompletionService 的线程不并行启动?

java - ExecutorService 为每个提交的任务指定使用新线程

java - Bash 中的依赖嵌套 For 循环