如何在线程运行 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();
}
}
最佳答案
您的问题没有唯一的答案。这取决于线程做什么。首先,您打算如何停止该线程?
- 如果它详细说明了一些东西,并且这些东西是由“ token ”组成的,例如要执行的单个“任务”,并且线程从
BlockingQueue
中获取它们,那么您可以停止带有所谓“毒丸”的线程,就像一个模拟任务,线程读作:“嘿伙计,我必须关闭”。 - 如果线程执行的操作无法“划分”为“步骤”,那么您实际上应该告诉我们您认为如何关闭它。如果它阻塞在套接字上的
read()
上,您只能关闭套接字以解除阻塞。
请注意 interrupt()
在正常情况下并不意味着停止一个 Thread
,如果你 interrupt()
一个线程,在大多数情况下,它会继续做它的事情。在 99.9% 的情况下,使用 interrupt()
停止线程只是糟糕的设计。
无论如何,要在 5 秒后停止它,只需设置一个 Timer
即可。或者更好的是 join
它,超时为 5 秒,然后停止它。问题是“如何”阻止它。所以请告诉我您认为应该如何停止线程,以便我可以更好地帮助您。
告诉我线程做了什么。
编辑:回复你的评论,只是一个例子
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
,因为我打赌可能会有一些竞争条件。
干杯。
关于java - 一段时间后停止线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7595490/