考虑 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 一直在说
you cannot interrupt a task that is trying to acquire a synchronized lock or one that is trying to perform I/O.
或者中断在这里意味着别的意思??
他还说
SleepBlock is an example of interruptible blocking, whereas IOBlocked and SynchronizedBlocked are uninterruptible blocking.
他这里说的不间断阻塞是什么意思?任何人都可以指定两者之间的区别吗?
最佳答案
他已经过时了,或者你的版本已经过时了。 NIO 支持可中断 I/O,通过 InterruptibleChannel
,尽管由于可笑的 Linux 中断语义, channel 只是以相当无用的方式关闭。
java.io
和 java.net
I/O 操作不受中断影响,并且您的问题中没有任何其他证据。如果是,您会在输出中看到 "Interrupted from blocked I/O"
,但您没有看到。您的 I/O 线程仍在 in.read()
中阻塞。
关于java - 什么是不间断阻塞?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47957606/