java - 中断的线程仍在继续执行

标签 java multithreading

我试图理解线程的行为,所以我编写了代码:

    public class Threads extends Thread {
        private Account account = new Account();
        public static void main(String[] args) {
            Threads t = new Threads();
            t.start();
            t.interrupt();
        }
   @Override
    synchronized public void run() {
        System.out.println("Running...");
        account.func();account.func2();
    }

}
class Account {

    public synchronized void func()  {
        try {
            System.out.println("func");
            wait(1000);
            System.out.println("hi func");
        } catch (InterruptedException ex) {
            System.out.println("Ex func");
        }
    }
    public synchronized void func2()  {
        try {
            System.out.println("func2");
           wait(2000);
            System.out.println(Thread.currentThread().isInterrupted());
            System.out.println("Hi func2");
        } catch (InterruptedException ex) {
            System.out.println("Ex func2");
        }
    }
}

输出是:

正在运行

函数

Ex函数

func2

错误

嗨 func2

所以我知道在等待锁定对象被通知时中断线程会抛出IntteruptedException但是我试图理解线程被中断为什么func 2仍然被正常调用甚至没有异常(exception) ?!!!! 以及为什么即使当前线程已经被中断,Thread.currentThread().isInterrupted()也会打印false

最佳答案

当你打电话时

t.interrupt();

Thread t 当前正在执行 wait(1000) 调用。这将导致您捕获InterruptedException。之后,继续正常执行。 func 方法返回并执行 func2 方法。

另外,请阅读 Thread#interrupt() 的 javadoc

If this thread is blocked in an invocation of the wait(), wait(long), or wait(long, int) methods of the Object class, or of the join(), join(long), join(long, int), sleep(long), or sleep(long, int), methods of this class, then its interrupt status will be cleared and it will receive an InterruptedException.

关于java - 中断的线程仍在继续执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20810570/

相关文章:

java - 使用 spring mvc 进行国际化

C# - 在 TextBox 上使用异步和等待的跨线程错误

c++ - Qt:qthread 在关闭期间线程仍在运行时被销毁

java - Java 中的用户定义值类是什么样的?

java - shell脚本没有完全从java执行

ruby - 在 Ruby 中运行多线程 Open3 调用

xcode - 如何在不阻塞主线程的情况下在 Xcode、单元测试中执行延迟?

multithreading - 如何获得多线程dot()函数?

java - 当 ie7 和 ie8 说 "to help protect your bla bla"时,我怎么能意识到?因为它阻止我的 servlet 将字节数组作为文件下载

java - 在本地抑制不必要的 stub 异常