销毁一个线程,在它的run()方法中有一个永不结束的函数



在我的线程类的run()方法中,我调用一个永不结束的函数。我需要线程只运行一个特定的持续时间。

我无法控制线程一旦启动,他们有什么办法摧毁它吗?

我试过yield(), sleep()等…

PS -我不能改变永不结束的功能

From 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()必须永远不会在线程上调用。

让一个长时间运行的方法响应中断是程序员的责任。

http://docs.oracle.com/javase/1.5.0/docs/guide/misc/threadPrimitiveDeprecation.html回答你所有的问题。我应该用什么来代替Thread.stop?

希望有所帮助

这可能太多了,但这就是我将如何解决它,如果你不想打乱中断。

 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();
    }
}
 }

基本上你是在一个ExecutorServie中包装你的可运行程序,如果它没有在间隔内完成,你基本上杀死它-发送中断给它。

最新更新