Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/377.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
当父线程被阻塞时,Java try catch是否使用闭包捕获终止的子线程?_Java_Timeout_Closures_Threadpoolexecutor_Cancellation - Fatal编程技术网

当父线程被阻塞时,Java try catch是否使用闭包捕获终止的子线程?

当父线程被阻塞时,Java try catch是否使用闭包捕获终止的子线程?,java,timeout,closures,threadpoolexecutor,cancellation,Java,Timeout,Closures,Threadpoolexecutor,Cancellation,我希望对这里提出的问题进行扩展: 给出下面的代码片段,我想知道TimeoutException的catch是否会在某种闭包中捕获超过timelimit的线程?即使主线程被终止阻塞,这些线程是否仍会捕获?这个实现似乎有效。。。但也许到目前为止我很幸运,没有僵局,也没有明显的比赛条件 public List<T> setupThreads() throws InterruptedException, ExecutionException { if (nThreads < 1

我希望对这里提出的问题进行扩展:

给出下面的代码片段,我想知道TimeoutException的catch是否会在某种闭包中捕获超过timelimit的线程?即使主线程被终止阻塞,这些线程是否仍会捕获?这个实现似乎有效。。。但也许到目前为止我很幸运,没有僵局,也没有明显的比赛条件

public List<T> setupThreads() throws InterruptedException, ExecutionException {
    if (nThreads < 1 || timeout < 1 || preRunObjects == null || preRunObjects.isEmpty()) {
        return null;
    }
    List<T> postRunObjects = new ArrayList<>();
    List<Future<T>> futures = new ArrayList<>();
    ExecutorService executor = Executors.newFixedThreadPool(nThreads);
    for (T runMe : preRunObjects) {
        futures.add(executor.submit(runMe));
    }
    for (Future<T> f : futures) {
        try {
            postRunObjects.add(f.get(timeout, TimeUnit.SECONDS));
        } catch (TimeoutException te) {
            log.warn("A thread has failed to run in time! It will be canceled.");
            if(!f.isDone()) {
                f.cancel(true);
                if(f.isCancelled()) {
                    log.info("Punishment complete!");
                }
            }
        }
    }
    executor.shutdown();
    executor.awaitTermination((timeout * postRunObjects.size()), TimeUnit.SECONDS);
    return postRunObjects;
}
我很想知道TimeoutException的捕获是否会在某种闭包中捕获超过时间限制的线程?即使主线程被终止阻塞,这些线程是否仍会捕获

以某种方式结束?这有关系吗

您的主线程不会调用executor.awaitTermination,直到for。。。循环已完成

还要注意:所有的f.get调用都是顺序的:主线程将为第一个结果等待最多超时秒,然后为下一个结果等待最多超时秒,…下一个,…下一个,…等等


这就是你的想法吗?或者您的意思是等待的时间不超过超时总秒数?

因为Java在Java 7之前没有闭包,并且从第一天起就有异常,我认为答案是否定的。主线程将在f.get上阻塞,等待终止只有在所有未来都超时或完成时才会运行。詹姆斯·拉格和贝文克对这个问题有正确的答案。也就是说,这个问题本身就被打破了。我错过了关于未来的部分。在文档中进行阻止。因此,在运行awaitTermination时,我已经运行并完成了每个子线程,并且所有线程都处于不会导致awaitTermination阻塞的状态。这将使它在代码段中变得毫无意义。然而,我现在有了一个更完整的画面。谢谢Elliott Frisch,实际上我从未尝试在6中使用闭包,现在我很高兴我没有/不会尝试!