在我的Thread类的run()
方法中,我正在调用一个永无止境的函数。
我需要线程只在特定的持续时间内运行。
一旦线程开始就无法控制线程,是否有任何方法可以销毁它?
我尝试了yield()
,sleep()
等等......
PS - 我无法改变永无止境的功能
答案 0 :(得分:2)
来自oracle Java Docs:
public void run(){
for (int i = 0; i < inputs.length; i++) {
heavyCrunch(inputs[i]);
if (Thread.interrupted()) {
// We've been interrupted: no more crunching.
return;
}
}
}
您的线程应在每次循环后检查中断条件以查看它是否被中断。如果你正在调用一个只执行while(true){}
的方法,那么我担心没有办法打断它,并且stop()
绝不能在一个线程上被调用。
程序员有责任制定一个响应中断的长时间运行方法。
答案 1 :(得分:0)
http://docs.oracle.com/javase/1.5.0/docs/guide/misc/threadPrimitiveDeprecation.html回答您的所有问题..特别是我应该使用什么而不是Thread.stop?
希望有所帮助
答案 2 :(得分:0)
这可能太多了,但如果你不想搞乱中断,这就是我解决它的方法。
public class ThreadTest {
public static void main(String[] args) throws InterruptedException {
ThreadTest test = new ThreadTest();
test.go();
}
void go() throws InterruptedException{
ExecutorService service = Executors.newSingleThreadExecutor();
service.execute(new LongRunnable());
if(!service.awaitTermination(1000, TimeUnit.MILLISECONDS)){
System.out.println("Not finished within interval");
service.shutdownNow();
}
}
}
class LongRunnable implements Runnable {
public void run(){
try{
//Simultate some work
Thread.sleep(2000);
} catch(Exception e){
e.printStackTrace();
}
}
}
基本上你将runnable包装在ExecutorServie中,如果它没有在间隔内完成,你基本上就把它杀了 - 发送它的中断。