日期:2014-05-20  浏览次数:20681 次

关于java定时任务的关闭,求高手打救
代码如下:

public class MonitoringTimer{

public static boolean flag=false;

public  boolean getFlag() {
return this.flag;
}

public void setFlag(boolean flag) {
this.flag = flag;
}



public void run(){
this.setFlag(true);
while(flag){
System.out.println("a");
try{
Thread.sleep(3000);
}catch(Exception e){
e.printStackTrace();
}
}
}

public void stop(){
this.setFlag(false);
}

public static void main(String[] args) {
MonitoringTimer m=new MonitoringTimer();
m.run();

}

}



当我运行了main方法之后,后台就每隔三秒就输出一个a,
那么如果我想在其他方法中调用一个方法可以跳出这个死循环,该怎么弄呢?
求高手赐教,小弟感激不尽。
------解决方案--------------------

public class MonitoringTimer extends Thread {

public MonitoringTimer() {
this.start();
}

public volatile boolean flag = false;

public boolean getFlag() {
return this.flag;
}

public void setFlag(boolean flag) {
this.flag = flag;
}

public void run() {
this.setFlag(true);
while (flag) {
System.out.println("a");
try {
Thread.sleep(3000);
} catch (Exception e) {
e.printStackTrace();
}
}
}

public void stopMonitor() {
this.setFlag(false);
}

public static void main(String[] args) throws InterruptedException {
MonitoringTimer m = new MonitoringTimer();

Thread.sleep(10000);

// 主线程调用关闭方法
m.stopMonitor();

}

}