Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/powerbi/2.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 ExecutorService-在指定的时间限制后终止线程_Java_Threadpool_Runnable_Executorservice_Threadpoolexecutor - Fatal编程技术网

Java ExecutorService-在指定的时间限制后终止线程

Java ExecutorService-在指定的时间限制后终止线程,java,threadpool,runnable,executorservice,threadpoolexecutor,Java,Threadpool,Runnable,Executorservice,Threadpoolexecutor,我已创建ExecutorService并提交了一份作业。这项工作可能很耗时。所以我给了timeout2秒。如果执行时间超过2秒,我想杀死该线程 public void threadTest() { ExecutorService executor = Executors.newSingleThreadExecutor(); try { executor.submit(() -> { try {

我已创建
ExecutorService
并提交了一份作业。这项工作可能很耗时。所以我给了
timeout
2秒。如果执行时间超过2秒,我想杀死该线程

public void threadTest() {
        ExecutorService executor = Executors.newSingleThreadExecutor();
        try {
            executor.submit(() -> {
                try {
                    String threadName = Thread.currentThread().getName();
                    Thread.sleep(7000);
                    System.out.println("process completed after 7 seconds");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }).get(2, TimeUnit.SECONDS);
        }catch (Exception e){
        }
        executor.shutdown();

    }

    public static void main(String[] args) throws Exception {
        System.out.println("main start");
        ThreadBreaker tb = new ThreadBreaker();
        tb.threadTest();
        System.out.println("main end");
    }
输出

main start
main end
process completed after 7 seconds

如我所料,函数
threadTest
在2秒后退出。但提交的作业仍在运行。如果提交的任务无法在给定的超时时间内完成,我希望停止该任务

一旦您向executorService提交了一个任务,您就拥有了一个未来的对象。您可以通过Future取消执行。取消(true)调用

请记住,如果在任务中有准确的中断异常处理,则可以取消活动的正在运行的任务

在上述示例中:

 Thread.sleep(7000); 

将引发一个中断的异常,而您不应该捕捉它(或者如果捕捉到它,则重新引发另一个异常)

当您使用
ExecutorService
时,您不能自行终止线程。ThreadPool决定何时终止
线程
(通常在
线程
中断时发生)

在您的情况下,您应该捕获
TimeoutException
cancel
未来的
。如果您的“真实”任务对中断有响应(正确调用和处理
InterruptedException
),它将工作。否则,您应该检查循环中的
Thread.currentThread().isInterrupted()
状态。 您的示例代码如下所示:

public void threadTest() {
    ExecutorService executor = Executors.newSingleThreadExecutor();
    Future<?> submit = executor.submit(() -> {
        try {
            String threadName = Thread.currentThread().getName();
            Thread.sleep(7000);
            System.out.println("process completed after 7 seconds");
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt(); //preserve interruption status. based on this ThreadPool's interruption Policy will decide what to do with the Thread
        }
    });

    try {
        submit.get(2, TimeUnit.SECONDS);
    } catch (InterruptedException | ExecutionException e) {
        e.printStackTrace(); //handle this
    } catch (TimeoutException e) {
        submit.cancel(true); //cancel the task
    }
    executor.shutdown();

}
public void threadTest(){
ExecutorService executor=Executors.newSingleThreadExecutor();
未来提交=执行者提交(()->{
试一试{
字符串threadName=Thread.currentThread().getName();
睡眠(7000);
System.out.println(“7秒后处理完成”);
}捕捉(中断异常e){
Thread.currentThread().interrupt();//保留中断状态。基于此线程池的中断策略将决定如何处理线程
}
});
试一试{
submit.get(2,TimeUnit.SECONDS);
}捕获(中断异常|执行异常e){
e、 printStackTrace();//处理此问题
}捕获(超时异常e){
submit.cancel(true);//取消任务
}
executor.shutdown();
}
还请记住,如果在线程池中执行任务,并且在大多数情况下执行可能来自
InterruptedException
的操作,则应保留中断状态