有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何在中断线程B时识别线程A的名称或任何上下文信息?

我发现了一个类似的问题:Interrupt with name identifier [Sigaction - Linux]

  1. 当线程A中断线程B时,如何识别线程A的名称或任何上下文信息
  2. 即使我们得到线程A的名称,也有可能有多个线程具有这里提到的相同名称:https://docs.oracle.com/javase/8/docs/api/java/lang/Thread.html#interrupt-- Every thread has a name for identification purposes. More than one thread may have the same name. If a name is not specified when a thread is created, a new name is generated for it.
  3. 这是否意味着我必须创建继承“java.lang.thread”的自定义线程

代码示例

Thread threadA = new Thread(new Runnable() {
public void run() {
    try {
      Thread.sleep(500);
    } catch (InterruptedException ex) { }
    System.out.println("I am going to interrupt, catch me if you can");
    threadB.interrupt();
  }
});

Thread threadB = new Thread(new Runnable() {
public void run() {
    try {
            System.out.println("threadB going to be interrupted");
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            //How to find name or any contextual info of threadA here?
            Thread.currentThread().interrupt();
        }
    
  }
});

threadB.start();
threadA.start();

如果无法直接实现,是否有任何解决方法或技巧


共 (1) 个答案

  1. # 1 楼答案

    我认为这不会像现在这样编译。一方面,系统。出来println不会抛出InterruptedException。我想你有个错误的想法叫threadB。中断()将导致threadB抛出InterruptedException。但它不会:它只会设置中断标志。请记住,InterruptedException是一个已检查的异常:它不是凭空出现的,必须有东西抛出它

    那么,撇开这一点不谈,你的例子离真正发生的事情有多近

    一般来说,如果你需要知道“谁设置了我的中断标志”,我认为没有任何简单的方法可以知道。如果您真的需要知道这一点,您可以使用Aspect4J之类的东西,并在保存该信息的interrupt()方法上嵌入建议

    但是,如果您对代码有更多的控制权(如上面的示例所示),那么答案是使用对象封装,让B不直接中断A,而是调用一个这样做的方法。实际上,我认为这是一种更好的实践,因为它可以让您自己的代码在中断的情况下完成它需要做的事情。这没有经过测试,但它的想法是:

    static class MyThread extends Thread {
      String interrupter;
    
      public void interrupt(String interrupter) {
        this.interrupter = interrupter;
        super.interrupt();
      }
    
      public void run() {
        while (!this.isInterrupted()) {
          // Do the thing
        }
        // Here you can see who interrupted you and do whatever
      }
    }