线程自我中断

时间:2014-03-24 12:35:15

标签: java multithreading

任务是创建一个免费的线程,当一段时间到期时它将被中断。我的代码根本不起作用。在休息点,我有无关紧要的线程。好吧,我已经结束了我的智慧。你能帮帮我吗?

public class HotThread implements Runnable {

    public HotThread() {
        this.file = null;        
    }
}


public class FreeThread extends HotThread {

    private final int timeout;
    Timer timer;
    InterruptByTimer task; 

    public FreeThread(int timeout) {
        super();
        this.timeout = timeout;
        timer = new Timer();
        task = new InterruptByTimer(timer);
        timer.schedule(task, timeout);
    }


    private class InterruptByTimer extends TimerTask {
        Timer timer;
        public InterruptByTimer(Timer timer){
            this.timer = timer;
        }

        @Override
        public void run(){
            interruptThisThread(timer);
        }
    }

    public void interruptThisThread(Timer timer){
            timer.cancel();
            Thread.currentThread().interrupt();
    }

}

2 个答案:

答案 0 :(得分:0)

来自java concurrency tutorial

  

线程通过调用Thread对象上的中断来发送中断,以便线程被中断。为使中断机制正常工作,中断的线程必须支持自己的中断。

此支持必须在您的线程运行方法中实现(我在您的代码中没有看到)。本教程中有几个例子。 run方法中的这类内容应该可以解决问题:

while( continueWork) {
    doSomeWork();
    if (Thread.interrupted()) {
        // We've been interrupted: no more crunching.
        return;
    }
}

要在timerTask中断你的线程,你需要有一个对它的引用,你可以将它传递给构造函数:

public class FreeThread extends HotThread {

    private final int timeout;
    Timer timer;
    InterruptByTimer task; 

    public FreeThread(int timeout) {
        super();
        this.timeout = timeout;
        timer = new Timer();
        task = new InterruptByTimer(timer, Thread.currentThread());
        timer.schedule(task, timeout);
    }

     private class InterruptByTimer extends TimerTask {
        Timer timer;
        Thread thread;
        public InterruptByTimer(Timer timer, Thread thread){
            this.timer = timer;
            this.thread = thread;
        }
        @Override
        public void run(){

            interruptThisThread(timer);
        }
    }

    public void interruptThisThread(Timer timer, Thread thread){
        timer.cancel();
        thread.interrupt();
    }

}
顺便说一句,我不明白为什么你把计时器传递给你的任务,因为无论如何cancel()都会调用interruptThisThread

答案 1 :(得分:0)

我认为问题在于Timer class in Java creates a background thread。因此,当您调用Thread.currentThread()时,它找到的实际线程和中断是计时器线程本身,而不是FreeThread。

要解决此问题 - 您应该将FreeThread作为构造函数参数传递给InterruptByTimer。将它存储为InterruptByTimer中的成员,然后当触发计时器时,您可以将其作为参数传递给interruptThisThread(当然,您必须更改该方法以接受线程参数)。然后在interruptThisThread中你可以调用传入的线程对象的中断。

Pierre Rust提出了一个有效的观点 - FreeThread的run方法必须通过检查Thread.interrupted()或捕获InterruptedException来支持中断。