考虑TIJ第4版中的此代码

class SleepBlocked implements Runnable {
  public void run() {
    try {
      TimeUnit.SECONDS.sleep(100);
    } catch(InterruptedException e) {
      print("InterruptedException");
    }
    print("Exiting SleepBlocked.run()");
  }
}

class IOBlocked implements Runnable {
  private InputStream in;
  public IOBlocked(InputStream is) { in = is; }
  public void run() {
    try {
      print("Waiting for read():");
      in.read();
    } catch(IOException e) {
      if(Thread.currentThread().isInterrupted()) {
        print("Interrupted from blocked I/O");
      } else {
        throw new RuntimeException(e);
      }
    }
    print("Exiting IOBlocked.run()");
  }
}

class SynchronizedBlocked implements Runnable {
  public synchronized void f() {
    while(true) // Never releases lock
      Thread.yield();
  }
  public SynchronizedBlocked() {
    new Thread() {
      public void run() {
        f(); // Lock acquired by this thread
      }
    }.start();
  }
  public void run() {
    print("Trying to call f()");
    f();
    print("Exiting SynchronizedBlocked.run()");
  }
}

public class Interrupting {
  private static ExecutorService exec =
    Executors.newCachedThreadPool();
  static void test(Runnable r) throws InterruptedException{
    Future<?> f = exec.submit(r);
    TimeUnit.MILLISECONDS.sleep(100);
    print("Interrupting " + r.getClass().getName());
    f.cancel(true); // Interrupts if running
    print("Interrupt sent to " + r.getClass().getName());
  }
  public static void main(String[] args) throws Exception {
    test(new SleepBlocked());
    test(new IOBlocked(System.in));
    test(new SynchronizedBlocked());
    TimeUnit.SECONDS.sleep(3);
    print("Aborting with System.exit(0)");
    System.exit(0);
  }
}


这是输出

Interrupting SleepBlocked
InterruptedException
Exiting SleepBlocked.run()
Interrupt sent to SleepBlocked
Waiting for read():
Interrupting IOBlocked
Interrupt sent to IOBlocked
Trying to call f()
Interrupting SynchronizedBlocked
Interrupt sent to SynchronizedBlocked
Aborting with System.exit(0)


在这里,您可以看到所有创建的线程最后都被中断了(这是我的想法,因为没有人执行它的run方法直到最后),但是在那之后,Bruce Eckel继续说


  您无法中断正在尝试获取同步的任务
  锁或试图执行I / O的锁。


还是在这里中断意味着其他东西?

他还说


  SleepBlock是可中断阻止的示例,而IOBlocked
  和SynchronizedBlocked是不间断的阻塞。


他在这里不间断地封锁是什么意思?谁能指定两者之间的区别?

最佳答案

他已经过时,或者您的版本已经过时。 NIO通过InterruptibleChannel支持可中断的I / O,尽管由于可笑的Linux中断语义,仅以相当无用的方式关闭了通道。

java.iojava.net I / O操作不受中断的影响,您的问题中没有什么可以证明是相反的。如果是的话,您将在输出中看到"Interrupted from blocked I/O",而您没有看到。您的I / O线程仍在in.read()中被阻止。

07-26 04:04