ExecutorService超时未按预期工作

时间:2016-05-22 14:44:34

标签: java

超时应该在一秒钟之后发生,但不会发生这种情况。

public class Worker implements Runnable {

    int workerId;

    public Worker(int workerId) {
        super();
        this.workerId = workerId;
    }

    public void run() {
        System.out.println(workerId+"Worker Started ....");
        try {
            Thread.sleep(20000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(workerId+"Worker finishes.....");
    }
}

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class TestExecutor {

    public static void main(String[] args) {
        ExecutorService executorService=Executors.newCachedThreadPool();
        for(int i=0;i<=2;i++){
            executorService.submit(new Worker(i));
        }
        executorService.shutdown();
        try {
            executorService.awaitTermination(1, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            System.out.println("Timeout Happen .....");
        }
    }
}

1 个答案:

答案 0 :(得分:0)

此代码

try {
    executorService.awaitTermination(1, TimeUnit.SECONDS);
} catch (InterruptedException e) {
    System.out.println("Timeout Happen .....");
}

没有做你期望的事情。

  

抛出:       InterruptedException - 如果在等待时被中断

来自javadocs

。您的代码不会在秒内终止,只有在线程被中断时,InterruptedException才会被抛出,而代码正在等待executorService终止。正确的等待来测试executorService实际终止是否

try {
    if(executorService.awaitTermination(1, TimeUnit.SECONDS))
        System.out.println("Terminated correctly");
    else
        System.out.println("Termination failed");
} catch (InterruptedException e) {
    e.printStackTrace();
}

并且executorService.shutdown()等待运行线程终止。因此,您的代码将等待整整20秒,直到提交的runnable终止并且在此期间不会接受或启动任何新的Runnables。如果要以不太优雅的方式终止Thread,则必须使用executorService.shutdownNow(),这将中断正在运行的线程。