Java,如何制作一个监视程序状态的线程?

Joe*_*e F 1 java multithreading state

我想创建一个在后台不断运行的线程,在运行时检查程序的状态.我只是想知道如何保持它运行以及如何制作线程.

Rya*_*art 6

Executors.newSingleThreadExecutor().submit(new ApplicationMonitor());

class ApplicationMonitor implements Runnable {
    public void run() {
        // do your monitoring stuff
    }
}
Run Code Online (Sandbox Code Playgroud)

ApplicationMonitor永远不应该返回,也绝不允许抛出异常.或者,也许更安全,让ApplicationMonitor只进行一次检查,并将submit()调用放在循环中.然后监视可能会失败,稍后将重新启动:

while (true) {
    try {
        Future<?> future = Executors.newSingleThreadExecutor().submit(
                    new ApplicationMonitor());
        future.get(); // can add a timeout here to limit the monitoring thread
    } catch (Exception e) {
        reportMonitoringException(e);
    }
    sleepUntilNextMonitoringCycle();
}
Run Code Online (Sandbox Code Playgroud)

最后,您可以让Java为您执行调度:

ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1);
executorService.scheduleWithFixedDelay(
    new ApplicationMonitor(), 0, 30, TimeUnit.MINUTES);
Run Code Online (Sandbox Code Playgroud)

使用这种方法,您无法获得所有计划调用的Future,因此您的异常必须在ApplicationMonitor中处理.