[英]How to run a method for a particular duration of time?
我讀了這個
您如何知道該方法是否成功完成或被中斷?
編輯 :為了使問題更清楚和具體。下面是我的代碼..我要為其執行test.java文件並獲取其運行時間。但是,如果要花費1秒以上的時間,我想顯示一條錯誤消息並停止它本身在那里..
public class cl {
public static void main(String args[])throws IOException
{
String s=null;
Process p=Runtime.getRuntime().exec("javac C:\\Users\\Lokesh\\Desktop\\test.java");
BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));
while ((s = stdError.readLine()) != null) {
System.out.println(s);
}
Timer timer=new Timer(true);
InterruptTimerTask interruptTimerTask=new InterruptTimerTask(Thread.currentThread());
timer.schedule(interruptTimerTask,1);
try{
Runtime.getRuntime().exec("java C:\\Users\\Lokesh\\Desktop\\test");
}
catch (Exception e)
{
e.printStackTrace();
}
finally {
timer.cancel();
}
}
static class InterruptTimerTask extends TimerTask {
private Thread thread;
public InterruptTimerTask(Thread thread)
{
this.thread=thread;
}
@Override
public void run()
{
thread.interrupt();
}
}
}
了解終止線程的最簡單方法是擁有一個布爾標志,將其稱為“ interrupted”,並在捕獲InterruptedException
時進行設置。 假設您的代碼沒有執行可能引發該異常的其他任何事情,則可以在隨后的代碼中檢查該標志的值。
例如:
try {
Thread.sleep(10000);
// method successfully completed
} catch (InterruptedException ex) {
// method was interrupted. You can try sleep some more time if you want
}
Thread.sleep()
是可以中斷的方法之一。 可以有其他方法替代,甚至可以檢查您的中斷狀態的方法。 如果您的方法意識到有人要中斷它,則必須拋出InterruptedException
(不是必須的,有時繼續運行會更好)。
中斷機制是使用內部標志(稱為中斷狀態)實現的。 調用Thread.interrupt設置此標志。 當線程通過調用靜態方法Thread.interrupted檢查中斷時,將清除中斷狀態。 一個線程用於查詢另一線程的中斷狀態的非靜態isInterrupted方法不會更改中斷狀態標志。
按照慣例,任何通過拋出InterruptedException退出的方法都會清除中斷狀態。 但是,總是有可能通過另一個調用中斷的線程立即再次設置中斷狀態。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.