异常情况 正常情况 i=-3: status=true M read A status = true i=-2: status=false M read A status = false i=-1: status=true M read A status = true A become Exception! M read A status = true M read A status = true M read A status = true A is deaded! M is restarting A! ____________________________ i=-3: status=false M read A status = false i=-2: status=true M read A status = true i=-1: status=false M read A status = false A become Exception! M read A status = false M read A status = false M read A status = false A is deaded! M is restarting A! ____________________________ i=-3: status=true M read A status = true i=-2: status=false M read A status = false i=-1: status=true M read A status = true A become Exception! M read A status = true M read A status = true M read A status = true Alert! A is unstable, M will stop it (结束) i=1: status=true M read A status = true i=2: status=false M read A status = false i=3: status=true M read A status = true i=4: status=false M read A status = false i=5: status=true M read A status = true A is Ending M M read A status = true (结束)
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! ____________________________ "); } } } else{ maydeadtimes = 0; } } }