![](/img/trans.png)
[英]Is this a correct way to stop a thread if it hasn't finished after a set period of time?
[英]Stop a thread after period of time
在運行5秒鍾后如何停止運行線程?
我無法使用Java 5+線程功能(必須在j2me中工作)。
可能的解決方案-
安排兩個線程。 一個執行實際工作(T1),另一個充當T1(T2)的監視器。
一旦T1開始,則啟動T2。 T2每秒在T1上調用isalive()方法,如果10秒鍾后T2沒有死亡,則T2在T1上調用中止,這將殺死T1線程。
這可行嗎?
Timer timer = new Timer();
TimerTask timerTask = new TimerTask() {
public void run() {
getPostData();
}
};
timer.schedule(timerTask, 0);
public void abortNow() {
try {
_httpConnection.close();
}
catch(Exception e){
e.printStackTrace();
}
}
您的問題沒有唯一的答案。 這取決於線程的功能。 首先,您打算如何停止該線程?
BlockingQueue
抓取了它們,那么您可以使用所謂的“毒葯”來停止線程,就像線程讀取的模擬任務一樣:“嘿,我必須關閉”。 read()
上阻塞,則只能關閉該套接字才能解除阻塞。 請注意, interrupt()
在正常情況下並不意味着要停止Thread
,並且如果您interrupt()
一個線程,則在大多數情況下它只會繼續執行其工作。 在99.9%的情況下,使用interrupt()
停止線程是不好的設計。
無論如何,要在5秒鍾后停止它,只需設置一個Timer
。 或者最好以5秒的超時時間join
它,然后將其停止。 問題是“如何”阻止它。 因此,請告訴我您如何停止線程,以便更好地為您提供幫助。
告訴我線程的作用。
編輯:回復您的評論,只是一個例子
class MyHTTPTransaction extends Thread {
public MyHTTPTransaction(.....) {
/* ... */
}
public void run() {
/* do the stuff with the connection */
}
public void abortNow() {
/* roughly close the connection ignoring exceptions */
}
}
接着
MyHTTPTransaction thread = new MyHTTPTransaction(.....);
thread.start();
thread.join(5000);
/* check if the thread has completed or is still hanging. If it's hanging: */
thread.abortNow();
/* else tell the user everything went fine */
:)
您還可以設置Timer
,或在Lock
上使用Condition
,因為我敢打賭,可能存在一些比賽條件。
干杯。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.