java如何動態(tài)執(zhí)行while循環(huán)
更新時間:2024年01月16日 09:35:59 作者:奈何、草
這篇文章主要介紹了java如何動態(tài)執(zhí)行while循環(huán)問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
問題描述
public void M1(int second){
boolean flag = true;
while(flag){
//執(zhí)行second秒后退出while循環(huán)
}
}實現(xiàn)思路
設置一個定時器執(zhí)行定時任務,到達指定時間后把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秒執(zhí)行一次while循環(huán)
System.out.println("executing.....");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("method end");
}
}執(zhí)行結果
executing.....
executing.....
executing.....
executing.....
executing.....
set end
executing.....
method end
總結
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
Spring Boot集群管理工具KafkaAdminClient使用方法解析
這篇文章主要介紹了Spring Boot集群管理工具KafkaAdminClient使用方法解析,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2020-02-02
Maven 版本管理與 flatten-maven-plugin 插件的使用解析
這篇文章主要介紹了Maven 版本管理與 flatten-maven-plugin 插件的使用解析,本文通過示例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-07-07
spring中REST和RESTful的區(qū)別以及基本實現(xiàn)
本文主要介紹了spring中REST和RESTful的區(qū)別以及基本實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2022-04-04

