实时多任务处理中,每个任务作为一个线程来运行。存在一个监控线程负责管理多个实时任务。实时任务存在出现异常的可能,因此监控线程需要能够及时发现异常的任务并进行处理。处理方式可能会随着异常出现的频率而不同,比如初次发生异常的任务可以通过重启任务来解决,经常发生异常的任务可以通过向管理员报警来解决。
监控线程通过读取任务的“心跳”信息来判断任务的状态,如果任务在一段时间间隔内没有更新“心跳”信息,监控线程就认为这个任务有可能发生了异常,当这种现象持续多次超过某一阈值时,就重启或者发出警报。
“心跳”信息可以有多种形式表示,只要监控线程可以阅读并且任务正常运行时可以周期性的更新“心跳”即可,程序中使用简单的状态变量表示心跳。
监控线程除了监控发生异常的线程以外还可以监控超时的任务,这时就需要记录任务开始运行的时间。
package safethread;
// 核心调度程序
public class mythread {
public mythread() { }
public static void main(String[] args) {
M m = new M();
}
}
// A 任务线程
class A extends Thread {
public static boolean dead = false;
M m;
A(M m){
m = m;
start();
}
public void run(){
try{
for(int i=-3;i<= 5;i++){
int j=1/i; // 人为设置过程中陷阱
dead = !dead; // 活动状态
System.out.println("i=" + i + ": status=" + dead);
try{
sleep(2000);
}
catch(InterruptedException ie){
System.out.println("A is Interrupted!");
}
}
m.Keepchecking = false; //A 正常结束后关闭监控线程
System.out.println("A is Ending M");
}
catch(Exception e){
System.out.println("A become Exception!");
}
}
}
// 监控线程
class M extends Thread{
public static boolean Keepchecking = true; // 持续监控标志
boolean laststatus; //保存上次监控状态
int maydeadtimes = 0; //监控线程可能死亡的计数器
int maydeadtimeout = 3;//定义判断线程死亡的边界条件
int deadtimes = 0; //监控线程死亡次数的计数器
int deadtimeout = 3; //定义判断线程不正常的边界条件
A a;
M(){start();}
public void run(){
schedule();
while(Keepchecking){
laststatus = a.dead;
try{
sleep(2000);
}
catch(InterruptedException e){
System.out.println("M is Interrupted!");
}
System.out.println("M read A status = " + a.dead);
if(laststatus == a.dead ){
if(++maydeadtimes >= maydeadtimeout){
if(++deadtimes >= deadtimeout){
System.out.println("Alert! A is unstable, M will stop it");
a = null;
break;
}
else{
System.out.println( "A is deaded!");
schedule();
System.out.println("M is restarting A!/n____________________________/n");
}
}
}
else{
maydeadtimes = 0;
}
}
}
private void schedule(){
a = new A(this);
}
}