在我们的应用程序中,我们有线程执行特定的操作。
收到事件后,我们需要中断正在进行的线程。
这些线程将通过调用“Thread.currentThread()。isInterrupted()”来检查其中断状态,
如果被中断,则线程通过从run方法返回来停止。

我们现在看到的问题是这些线程可以在对象上使用wait()。
如果线程在对象的wait()时中断,
线程中断状态被重置,并抛出InterruptedException。

自从
1)我们有很多地方线程可以在一个对象上等待
2)线程访问可以在一个对象上等待的其他对象的方法

我们已决定改写interrupt()和isInterrupted()方法。
该代码看起来像

public class MyThread extends Thread {

    private boolean isInterrupted = false;

    @Override
    public void interrupt() {
        isInterrupted = true;
        super.interrupt();
    }

    @Override
    public boolean isInterrupted() {
        return isInterrupted;
    }

    public void run() {
        .........
        .........

        try {
            object1.wait();
        } catch (InterruptedException e) {
            /* if interrput() is not overrided, the interrupted flag
            would be reset */
        }

        if(Thread.currentThread().isInterrupted()) {
            /* if interrupt is not overrided, isInterrupted would return
            false and the thread would continue to run. */
            return;
        }

        object2.method1(); // method1() can also wait on another object
        /* In method1() also we would need to check isInterrupted and get out
        quickly as soon as possible. This method1() will also be used by
        other threads which will not be interrupted. */

        if(Thread.currentThread().isInterrupted()) {
            return;
        }
        .........
        .........
    }
}

所以我的问题是

1)重写上面的interrupt()和isInterrupted()是编码的好习惯吗?

2)在覆盖interrupt()时,我们应该保持相同的行为,即throw
中断和其他异常,如interrupt()方法的Java文档中所述
在线程类?实际上我们需要等待被中断的线程
但要设置中断标志。

3)Thread.interrupted()方法是静态的。
有了上面的覆盖,我们不应该使用这种方法吧?

最佳答案

首先,重写这些方法是一个非常糟糕的主意。

其次,我不明白你为什么要让自己的生活如此艰难:

try {
  doSomethingThatCanBlock();// e.g. wait()
}
catch(InterruptedException ex) {
  Thread.currentThread().interrupt(); // restore interrupt state
}

现在,下次您检查Thread的中断状态时,它将告诉您适当的状态。而已。

关于java - 在线程类中重写Interrupt和isInterrupted方法,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23369891/

10-14 23:56
查看更多