繁体   English   中英

为什么我的线程在捕获异常时不创建一个新线程?

[英]Why doesn't my Thread create a new one when it catches an Exception?

所以我有一个像这样运行的线程:

Runnable runnable = new Runnable() {
                        @Override
                        public void run() {
                            System.out.println("redo groupMonitor ... ");
                            if (redogmSafer < 1) {
                                groupMonitor.run(remoteHost, port);
                            } else {
                            }
                            redogmSafer = 100;
                        }
                    };
ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
service.scheduleAtFixedRate(runnable, 0, delayStart, TimeUnit.MILLISECONDS);

if (redogmSafer < 1) {
} else {
    service.shutdown();
    service.shutdownNow();
    redogmSafer = 0;
}

我想再次run() Thread ,在它因异常或其他原因退出后(发生所有 4-5 小时)。

我曾尝试shutdown()shutdownNow() ,但这也无济于事。 就像 Java 不想在线程启动和关闭后重做线程......

您可以像这样创建一个新线程:

Thread newThread = new Thread(runnable);

newThread.start();

或使用 ExecutorService:

ExecutorService executorService = Executors.newCachedThreadPool();
executorService.execute(runnable);

但是您已经在使用应该完成这项工作的 ScheduledExecutorService。

用 try-catch 包装您的Runnable / Callable代码

ScheduledExecutorService在接收到ThrowableExceptionError )时会停止进一步的调度。 这种停止是无声的,没有错误报告,也没有消息或日志记录。

因此,您应该着眼于预防问题而不是解决问题。 预防措施是用 try-catch 包装您的Runnable / Callable代码。

只要没有Throwable冒泡调用堆栈到达调度的执行器服务,调度就会继续。

Runnable runnable = new Runnable() {
                        @Override
                        public void run() {
                            try{
                                System.out.println("redo groupMonitor ... ");
                                if (redogmSafer < 1) {
                                    groupMonitor.run(remoteHost, port);
                                } else { 
                                    …
                                }
                                redogmSafer = 100;
                            } catch ( Exception e ) { … }
                        }
                    };

是否捕获ThrowableException或一些更具体的异常取决于您和您的团队根据您的情况来决定。

这个话题已经在 Stack Overflow 上讨论过多次。 搜索以了解更多信息。 具体来说,请参阅ScheduledExecutorService 异常处理

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM