我在我的程序JAVA:如何中斷,如果它持續超過1秒
for(int i = 0; i < 100000; i++) {
func(i);
}
對於我的大多數值有這樣的代碼,FUNC持續不到1秒,但對於一些價值可能持續功能幾分鐘,所以如果持續時間太長,我需要中斷它。
我該怎麼做?
我在我的程序JAVA:如何中斷,如果它持續超過1秒
for(int i = 0; i < 100000; i++) {
func(i);
}
對於我的大多數值有這樣的代碼,FUNC持續不到1秒,但對於一些價值可能持續功能幾分鐘,所以如果持續時間太長,我需要中斷它。
我該怎麼做?
中斷可能花費太長時間的函數的一種方法是通過在單獨的線程中運行它。然後您可以在一秒鐘後向該線程發送消息,告訴其停止。如果不使用線程,你可以用下面的代碼替換FUNC處理:
function process(int i, long maxMiliseconds) {
long start = System.currentTimeMillis();
while(System.currentTimeMillis() - start < maxMiliseconds) {
//do your processing one step at a time
// return an answer if you have one.
}
//make some record of the fact that the process timed out for i.
return;
}
你可以開始FUNC()在一個單獨的線程,然後做你的線程方法join(long millis)
等待1秒它的結束。但線程仍會運行直到完成(stop()
方法已過時)。這意味着要在當前線程中獲得控制權並做出適當的反應。
這就是我看到它的方式。我確信有辦法用較少的代碼行來做,但這是一個簡單的解決方案
如果你想在Thread
運行你的func(i);
那麼這將是另一回事。
public class MainClass {
private static boolean riding, updated = false;
private static int timeout = 10000;
public static void main(String[] args) {
while (true) {
if (!riding){
long endTimeMillis = System.currentTimeMillis() + timeout;
func(endTimeMillis);
}
}
}
private static void func(long endTimeMillis) {
for (int i = 0; i < 9999; i++) {
if ((!riding && System.currentTimeMillis() < endTimeMillis) || updated) {
updated = false;
System.out.println("run method main function");
riding = true;
} else {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(System.currentTimeMillis() + " > "
+ endTimeMillis);
if (System.currentTimeMillis() > endTimeMillis) {
updated = true;
System.out.println("overdue");
riding = false;
break;
}
}
}
riding = false;
}
}
如果你不想另一個線程,你可以注入你的異常處理到func中。
public static void main(String[] args)
{
try
{
func(1);
}
catch (timeR e)
{
System.out.println("enough!")
// TODO Auto-generated catch block
e.printStackTrace();
}
}
static void func(int a) throws timeR //your func needs to throw something when time-is-up
{
long time1,time2; //reference time and current time
time1=System.nanoTime(); //having reference
time2=System.nanoTime(); //init of current
while(true) //You did not put your func, so I used inf-while
{
//here whatever your func does,
//.....
//.....
//below line checks if time is up
time2=System.nanoTime();
if((time2-time1)>1000000000) //1000000000 is 1 second or 1Billion nanoseconds
{ throw new timeR("time is up!");}
//this is throwing(an alternative exit from this function)
}
}
static class timeR extends Exception
{
//Parameterless Constructor
public timeR()
{
}
//Constructor that accepts a message
public timeR(String message)
{
super(message);
}
}
輸出:FUNC後1秒()調用:
enough!
proje.lineerCebir$timeR: time is up!
at proje.lineerCebir.func(lineerCebir.java:198)
at proje.lineerCebir.main(lineerCebir.java:179)
也許你不想看到紅色消息,然後只是註釋掉e.printStackTrace()。 玩得開心。
FutureTask非常適合執行超時的代碼。
FutureTask task = new FutureTask(new Callable() {
@Override
public Object call() throws Exception {
/* Do here what you need */
return null; /* Or any instance */
}
}) {
};
try {
Object result = task.get(1, TimeUnit.SECONDS);
} catch (InterruptedException ex) {
Logger.getLogger(Example1.class.getName()).log(Level.SEVERE, null, ex);
} catch (ExecutionException ex) {
Logger.getLogger(Example1.class.getName()).log(Level.SEVERE, null, ex);
} catch (TimeoutException ex) {
Logger.getLogger(Example1.class.getName()).log(Level.SEVERE, null, ex);
}
}
'func(int i)'做了什麼?你可能會限制這段代碼的整體執行時間(有些時候),但是如果在特定的'func(i)'調用中花費了太多時間,這聽起來像你想限制一個單獨的調用並繼續下一個調用。 –
我不能做func(i)裏面的任何事情。它根據輸入產生僞隨機數字序列。還有另一種方法可以做到嗎? – user2282875
顯示你的func方法 – stinepike