【问题标题】:Future is halting rest of program execution未来正在停止其余的程序执行
【发布时间】:2017-06-14 18:57:01
【问题描述】:

我正在尝试从主线程并行执行 2 个作业,但如果回调方法需要很长时间才能给出响应,其余请求将暂停并等待首先完成。

这是我的代码:

 private final ExecutorService executorService = Executors.newFixedThreadPool(10);

 private void executeService(String uuid) {
    System.out.println("query executed done: " + uuid);
} 

 private String getAsynchTest(final String uuid) throws Exception {
    testAsynchF = executorService.submit(
            new Callable<String>() {
                public String call() throws Exception {
                    executeService(uuid);
                    return getFutuerResult(uuid, Thread.currentThread()); // long processing
                }
            });
    return testAsynchF.get();
}

public String getFutuerResult(String uuid, Thread t) {
    String dummy = "your result for request: "+uuid;
     if (uuid.equalsIgnoreCase("112")) {
        try {
            t.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    return dummy;
}

 public static void main(String[] args) {
    SynchronousTimeoutTester tester = new SynchronousTimeoutTester();

    try {
        String one = "112"
        System.out.println("Result sync call:*** " + tester.getAsynchTest(one));

        String two = "115";
        System.out.println("Result sync call:**** " + tester.getAsynchTest(two));

    } catch (Exception e) {
        System.out.println("catched as Exception: " + e);
    }

 }

如果请求 112 线程暂停,为什么会停止执行请求 115?

【问题讨论】:

  • 这不会编译...具体是什么executeService(String)getFutureResult(String)的实现?
  • executeService 方法未列出,getFutuerResult 需要一个 Thread 参数,main 中有一行缺少分号
  • tester.shutdown() 也未指定
  • 删除关闭方法调用..问题更新

标签: java multithreading future executorservice


【解决方案1】:

由于您将Thread.currentThread() 传递给getFutureResult,并且该方法在其线程参数上调用join()(如果uuid 为“112”),该方法将等待其自己的线程结束,但它不能因为它正在等待。

【讨论】:

  • 好的。如果我想暂停请求 112 进行测试并允许请求 115 继续进行,你能告诉我一件事,那么我应该在哪里添加这个加入?
  • 如果你想同时执行多个工作,但不关心结果的顺序,想在结果进来的时候处理,我建议你看看CompletionServices。跨度>
  • 好的。你能告诉我如何在回调方法中休眠任何请求(ex=112)的线程吗?
猜你喜欢
  • 2017-10-08
  • 1970-01-01
  • 1970-01-01
  • 2011-01-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-21
相关资源
最近更新 更多