项目中有这样一个场景,后台中运行着几组不同的生产线程,每组后台线程负责生产不同的资源,填充到不同阻塞队列中,供业务代码异步调用,以提高程序运行速度。为保证资源的正常生产,需要保证每组后台生产线程出现异常终止情况时,可以被较为即时的拉起,这时就需要对后台生产线程进行心跳监控。以下为线程监控的代码:
package com.dear.simple.queue;
import java.lang.Thread.State;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.apache.log4j.Logger;
/**
*
* @author lixiang
*
*/
public class ThreadMonitor implements Runnable{
private static final Logger LOG = Logger.getLogger(ThreadMonitor.class);
private List<Thread> monitoredThreads; //被监控的线程
public ThreadMonitor(List<Thread> monitoredThreads) {
this.monitoredThreads = monitoredThreads;
}
public void monitor(){
for (Thread thread : monitoredThreads) {
String tName = thread.getName();
State tState = thread.getState();
if(Thread.State.TERMINATED.equals(tState)){ //若被监控的线程为终止状态,则对其进行重启
LOG.info("describe : " + tName + "is terminated,start this thread");
thread.start();
LOG.info("describe : " +"start the thread " + tName + " success");
}
}
}
@Override
public void run() {
while(true){
monitor();
try {
TimeUnit.MILLISECONDS.sleep(2000);
} catch (InterruptedException e) {
LOG.error("describe : " + "thread monitor error : " + e.getMessage());
}
}
}
}
在系统启动时,初始化并开启监控线程ThreadMonitor,并将需要被监控的线程列表传入,这时,监控线程就可以定期的检查后台线程的运行情况了。