【问题标题】:Can one thread interrupts another thread?一个线程可以中断另一个线程吗?
【发布时间】:2015-11-27 06:48:25
【问题描述】:

我想知道在第一个线程的 run 方法中中断另一个线程是否非法。如果是,当我在第一个线程的run方法中调用另一个线程的中断方法时,会抛出“InterruptedException”吗?像这样:

public static void main(String[] args) {

    Thread thread1 = new Thread(() -> {
        while (true) {

        }
    }, "thread1");
    try {
        thread1.sleep(10000);
    } catch (InterruptedException e) {
        System.out.println("Oops! I'm interrupted!"); 
    }
    Thread thread2 = new Thread(() -> {
        System.out.println("I will interrupt thread1!");
        thread1.interrupt();
        System.out.println("Thread1 interruption done!");
    }, "thread2");
    thread1.start();
    thread2.start();
}

但我没有收到消息“糟糕!我被打断了!”在控制台中。

【问题讨论】:

  • 您应该在 thread1.sleep() 行上收到“通过实例访问静态方法”警告。这是在警告您 Keppil 在他们的回答中所说的内容
  • 我有这个。一路走来非常感谢! --)

标签: java multithreading interrupt


【解决方案1】:

你的程序不工作的原因是你使用thread1引用来访问静态的sleep()方法,但是睡眠仍然在主线程中执行。
将它移到thread1 的正文中,你的程序就可以正常工作了:

public static void main(String[] args) {
    Thread thread1 = new Thread(() -> {
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            System.out.println("Oops! I'm interrupted!");
        }
    }, "thread1");

    Thread thread2 = new Thread(() -> {
        System.out.println("I will interrupt thread1!");
        thread1.interrupt();
        System.out.println("Thread1 interruption done!");
    }, "thread2");
    thread1.start();
    thread2.start();
}

这打印:

I will interrupt thread1!
Thread1 interruption done!
Oops! I'm interrupted!

请注意,最后两个打印输出的顺序取决于线程调度,并且可能会有所不同。

【讨论】:

  • 太棒了!非常感谢你!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-08-30
  • 1970-01-01
  • 1970-01-01
  • 2021-03-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多