首页 \ 问答 \ 执行者与线程(Executors vs threads)

执行者与线程(Executors vs threads)

我正在尝试运行以下代码片段:

public static void main(String[] args){
    ScheduledExecutorService service = new ScheduledThreadPoolExecutor(2);

    Runnable r = new Runnable() {
        @Override
        public void run() {
            throw new RuntimeException();
        }
    };
    service.execute(r );
    ScheduledFuture<?> schedule = service.schedule(r, 0, TimeUnit.SECONDS);
    new Thread(r).run();
}

关于以上问题,我有以下问题:

  1. 有什么方法可以捕捉并回应执行者线程上发生的异常?
  2. 为什么创建的线程中的异常显式传播到主线程,但是使用executor服务执行的两个执行不会传播该错误? 这个错误怎么能被发现?

编辑:想到另一个问题:

  1. 我如何停止一个给定的定期任务,比如在N次重复或N分钟之后呢?

I am trying to run the following piece of code:

public static void main(String[] args){
    ScheduledExecutorService service = new ScheduledThreadPoolExecutor(2);

    Runnable r = new Runnable() {
        @Override
        public void run() {
            throw new RuntimeException();
        }
    };
    service.execute(r );
    ScheduledFuture<?> schedule = service.schedule(r, 0, TimeUnit.SECONDS);
    new Thread(r).run();
}

Regarding the above I have the following questions:

  1. Is there any way to catch and respond to exceptions happening on the executor's thread?
  2. Why is the exception from the thread created explicitly propagated to the main thread, but both executions using the executor service does not propagate that error? How can this error ever be discovered?

EDIT: One further question came to mind:

  1. How can i stop a given periodic task that I schedule, let's say after N repeats or N minutes?

原文:https://stackoverflow.com/questions/12809185
更新时间:2022-03-27 11:03

最满意答案

正在调用管道的未初始化或未分配的变量。 该变量在服务调用填充之前不存在。 检查管道中的输入是一个很好的习惯。

为你的管道添加一个检查以确认变量是否有值。

if(!tel) return "";

The pipe is being called for an uninitialized or unassigned variable. The variable does not exist until it is populated by the service call. Checking input in your pipes is a great habit.

Add a check to your pipe for the following which will verify that the variable has a value.

if(!tel) return "";

相关问答

更多
  • 当一个窗口关闭时,Chrome首先将window.console设置为null ,然后是window 。 下面的代码将通过创建一个引用不同上下文的window的函数来可靠地重现错误: var w = window.open('/'); // Using document.write to run code in the context of the other window w.document.write('