java如何动态执行while循环
作者:奈何、草
这篇文章主要介绍了java如何动态执行while循环问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
问题描述
public void M1(int second){ boolean flag = true; while(flag){ //执行second秒后退出while循环 } }
实现思路
设置一个定时器执行定时任务,到达指定时间后把flag的值设置成false
代码
import java.util.Timer; import java.util.TimerTask; public class Main { public static void main(String[] args) throws Exception { Timer timer = new Timer();//定时器 int delay = 5;//秒 Provider pd = new Provider(timer); pd.M1(delay); Thread.sleep(delay+100); timer.cancel();//注销定时器,否则虚拟机不退出 } } class Provider{ private Timer timer = null; public Provider(Timer timer){ this.timer = timer; } public void M1(int second) { // TODO Auto-generated method stub class ScheduleHelper{ public boolean flag = true; } final ScheduleHelper helper = new ScheduleHelper();//final内部类才能调用 timer.schedule(new TimerTask() { @Override public void run() { System.out.println("set end"); helper.flag = false;//设置结束 } }, second*1000); while (helper.flag) { try { Thread.sleep(1000);//1秒执行一次while循环 System.out.println("executing....."); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } System.out.println("method end"); } }
执行结果
executing.....
executing.....
executing.....
executing.....
executing.....
set end
executing.....
method end
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。