简体   繁体   English

监视线程状态

[英]Monitor thread status

So I have this very relevant thread I start when the program starts. 因此,我有一个与程序启动时非常相关的线程。 The thread is listening to events coming from a bigger system as the main thread does other stuff. 线程正在侦听来自更大系统的事件,而主线程则在做其他事情。 The thread should never stop working and if it does, it should be recreated and started. 该线程永远都不应停止工作,如果确实如此,则应重新创建并启动它。

I think I know multiple ways to achieve this, but I'd like to know your opinion on some things : 我想我知道实现此目标的多种方法,但我想了解您对某些事情的看法:

  • Am I just striving for nothing? 我只是在努力吗? I mean, if I ideally try-catch all the code that can go wrong, will the thread ever betray me for no obvious reason? 我的意思是,如果我理想地尝试捕获所有可能出错的代码,那么该线程会无缘无故地背叛我吗?
  • What's the best practice to do what I stated? 我所说的最佳做法是什么? Periodically check the thread health with another thread and a ScheduledExecutor? 定期检查另一个线程和ScheduledExecutor的线程运行状况吗? Implement some kind of observable-observer pattern? 实现某种可观察的观察者模式?

You can create the ExecutorService which is listening to the events via Executors.newSingleThreadExecutor() . 您可以通过Executors.newSingleThreadExecutor()创建ExecutorService来监听事件。 In that case You don't have to take a look at the thread if it is healthy, the ExecutorService takes care of that. 在这种情况下,如果线程运行状况良好,则不必查看该线程,ExecutorService会处理该线程。 The SingleThreadExecutor is responsible that only one Task (Runnable or Callable) is running at one time. SingleThreadExecutor负责一次仅运行一个任务(可运行或可调用)。

If you are checking using normal Java provided methods to view the thread state correctly, you should not have any errors. 如果要使用正常的Java提供的方法检查以正确查看线程状态,则应该没有任何错误。 In the case that a checked exception is thrown or the thread exits for some weird reason, a try-finally block should be sufficient to start a new thread (also ensure it is non-daemon). 如果抛出了检查异常或线程出于某种奇怪的原因退出,则try-finally块应足以启动新线程(还应确保它是非守护程序)。 You could use a while loop with a periodic pause, preferably using a thread scheduling mechanism such as timed wait(...) , or timed LockSupport#park(...) . 您可以使用带有周期性暂停的while循环,最好使用线程调度机制,例如LockSupport#park(...) wait(...)或timed LockSupport#park(...) You can also sleep the thread as well. 您也可以休眠线程。

The thread should never stop working and if it does,... 线程永远都不应停止工作,如果可以,...

OK, so write it so that it will never stop working. 好的,因此编写它,使其永远不会停止工作。

public void run() {
    while (true) {
        try {
            Message message = receiveNextMessage();
            handleMessage(message);
        } catch (Exception ex) {
            LOGGER.error(ex);
            if (somethingTrulyHorribleHasHappened(ex)) {
                Runtime.getRuntime().exit(1);
            } else {
                maybeResetSomethingThatNeedsToBeReset();
            }
        }
    }
}

This is a somewhat pointless and futile exercise. 这是一个毫无意义且徒劳的练习。 An app-lifetime thread should be debugged and made to not stop. 应用程序生存期线程应进行调试并使其不停止。 The main thread of your app lasts for the process lifetime and any other threads should be designed, tested and debugged to the same standard. 您的应用程序的主线程会持续整个进程生命周期,所有其他线程都应按照相同的标准进行设计,测试和调试。

What would happen if the thread that stopped had corrupted data in other threads when it crashed? 如果停止的线程崩溃时在其他线程中破坏了数据,将会发生什么? If you just restarted it somehow, the data corruption may well make the situation worse. 如果只是以某种方式重新启动它,则数据损坏很可能使情况变得更糟。

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

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