相关疑难解决方法(0)

什么是Java中的守护程序线程?

任何人都能告诉我Java中的守护程序线程是什么吗?

java multithreading

770
推荐指数
15
解决办法
45万
查看次数

处理Java ExecutorService任务中的异常

我正在尝试使用Java的ThreadPoolExecutor类来运行具有固定数量线程的大量重量级任务.每个任务都有许多地方,在这些地方可能因异常而失败.

我已经进行了子类化,ThreadPoolExecutor并且我已经覆盖了该afterExecute方法,该方法应该在运行任务时提供任何未捕获的异常.但是,我似乎无法使其发挥作用.

例如:

public class ThreadPoolErrors extends ThreadPoolExecutor {
    public ThreadPoolErrors() {
        super(  1, // core threads
                1, // max threads
                1, // timeout
                TimeUnit.MINUTES, // timeout units
                new LinkedBlockingQueue<Runnable>() // work queue
        );
    }

    protected void afterExecute(Runnable r, Throwable t) {
        super.afterExecute(r, t);
        if(t != null) {
            System.out.println("Got an error: " + t);
        } else {
            System.out.println("Everything's fine--situation normal!");
        }
    }

    public static void main( String [] args) {
        ThreadPoolErrors threadPool = new …
Run Code Online (Sandbox Code Playgroud)

java multithreading exception executorservice threadpoolexecutor

201
推荐指数
6
解决办法
15万
查看次数

在TimeoutException之后如何让FutureTask返回?

在下面的代码中,我按照预期在100秒后捕获TimeoutException.此时我希望代码退出main并终止程序,但它会继续打印到控制台.如何让任务在超时后停止执行?

private static final ExecutorService THREAD_POOL = Executors.newCachedThreadPool();

private static <T> T timedCall(Callable<T> c, long timeout, TimeUnit timeUnit) throws InterruptedException, ExecutionException, TimeoutException {
    FutureTask<T> task = new FutureTask<T>(c);
    THREAD_POOL.execute(task);
    return task.get(timeout, timeUnit);
}


public static void main(String[] args) {

    try {
        int returnCode = timedCall(new Callable<Integer>() {
            public Integer call() throws Exception {
                for (int i=0; i < 1000000; i++) {
                    System.out.println(new java.util.Date());
                    Thread.sleep(1000);
                }
                return 0;
            }
        }, 100, TimeUnit.SECONDS);
    } catch (Exception e) {
        e.printStackTrace();
        return;
    }


}
Run Code Online (Sandbox Code Playgroud)

java futuretask

9
推荐指数
1
解决办法
2万
查看次数