什么是不间断阻塞?

时间:2017-12-24 02:24:39

标签: java multithreading thread-safety

考虑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是不间断阻止。

这里的不间断阻挡是什么意思?任何人都可以指定两者之间的差异吗?

1 个答案:

答案 0 :(得分:0)

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

java.iojava.net I / O操作不会受到中断,并且您的问题中没有任何内容可以证明不是这样。如果是的话,你会在输出中看到"Interrupted from blocked I/O",而你却没有。您的I / O线程仍在in.read()中被阻止。