【发布时间】:2020-02-11 07:19:20
【问题描述】:
Thread.interrupt():
中断这个线程。除非当前线程 正在中断自己,这始终是允许的,checkAccess 调用此线程的方法,可能会导致 SecurityException 被扔掉。
如果该线程在调用 wait()、wait(long) 时被阻塞, 或 Object 类或 join() 的 wait(long, int) 方法, join(long)、join(long, int)、sleep(long) 或 sleep(long, int)、方法 这个类,那么它的中断状态将被清除,它会 收到一个 InterruptedException。
如果此线程在 I/O 操作中被阻塞 InterruptibleChannel 则通道将被关闭,线程的 中断状态将被设置,线程将收到一个 ClosedByInterruptException。
如果该线程在 Selector 中被阻塞,则该线程的中断 状态将被设置,它将立即从选择中返回 操作,可能具有非零值,就像选择器的 唤醒方法被调用。
如果前面的条件都不成立,那么这个线程的中断 状态将被设置。
中断一个不活跃的线程不需要有任何效果。
假设我们有这个代码:
AtomicBoolean thread1Done = new AtomicBoolean(false);
//write in file
Thread thread1 = new Thread(() -> {
try(var writer = Files.newBufferedWriter(Paths.get("foo.txt"))){
for(int i = 0; i < 10000; i++){
writer.write(i);
writer.newLine();
}
}catch(Exception e){ e.printStackTrace(); }
thread1Done.set(true);
});
//interrupt thread1
Thread thread2 = new Thread(() -> {
while(!thread1Done.get()){
thread1.interrupt();
}
});
thread2.start();
thread1.start();
thread1 永远不会在文件中写入任何内容,因为来自thread2 的thread1.interrupt()。
在writer.newLine(); 处总是以java.nio.channels.ClosedByInterruptException 结尾,而foo.txt 为空。
有没有办法只打断wait, join and sleep,而忽略其余的?
我在 Windows10 x64 上使用 JDK10 运行我的代码。
【问题讨论】:
-
当我运行你的代码时,我假设我得到了同样的异常,不像
@diginoise。默认情况下,它似乎使用可中断的通道。但是,根据您的问题,我假设您希望此 I/O 读取部分(或者这只是其他示例?)是不间断的? -
最简单的解决方案是不使用
java.nio包中的类,正如 answer 所示。 -
直接使用
BufferedWriter,而不是通过Files。
标签: java multithreading