什么是不间断阻塞?

问题描述 投票:1回答:1

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

这里的不间断阻挡是什么意思?谁能指定两者之间的差异?

java multithreading thread-safety
1个回答
0
投票

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

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

© www.soinside.com 2019 - 2024. All rights reserved.