分类:
2008-09-09 15:19:31
5. 源代码:
// 核心调度程序 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 a = new A(this); } }
[3]