2 回答

TA貢獻1806條經(jīng)驗 獲得超8個贊
如果您想要的是僅在線程被 wait、join 和 sleep 調(diào)用阻塞而不是 IO 操作時中斷線程,您可以在調(diào)用中斷方法之前簡單地檢查線程狀態(tài)。您可以參考以下鏈接中的 api 和不同狀態(tài)。
https://docs.oracle.com/javase/10/docs/api/java/lang/Thread.State.html
示例代碼可能如下所示。
while ( ( thread1.getState() == Thread.State.WAITING || thread1.getState() == Thread.State.TIMED_WAITING ) && !thread1Done.get()) { thread1.interrupt(); }

TA貢獻2051條經(jīng)驗 獲得超10個贊
按照目前的情況,您的代碼運行完成將Thread 110k 行寫入輸出文本文件,換句話說是中斷,但其中Thread 2沒有可中斷的語句。這是因為(我想)使用不間斷 I/O打開文件。Thread 1BufferedWriter
如果您希望長循環(huán)是Thread 1可中斷的,您可以在長時間運行的循環(huán)中添加以下檢查:
for(int i = 0; i < 10000; i++){
if (Thread.currentThread().isInterrupted()) { //interruptible loop
break;
}
writer.write(i);
writer.newLine();
System.out.println(i);
}
然后,通過將中斷延遲Thread 210 毫秒,我發(fā)現(xiàn)只有幾百個條目被寫入文件(沒有延遲,它會立即中斷)。
當我切換Thread 1為使用可中斷通道
時(按原樣FileChannel extends AbstractInterruptibleChannel):
Thread thread1 = new Thread(() -> {
FileChannel fc = null;
try (
FileChannel fc = FileChannel.open(Paths.get("foo.txt"),
StandardOpenOption.CREATE, StandardOpenOption.WRITE);
)
{
fc = FileChannel.open(Paths.get("foo.txt"),
StandardOpenOption.CREATE, StandardOpenOption.WRITE
);
for(int i = 0; i < 10000; i++){
fc.write(ByteBuffer.wrap(("" + i).getBytes()));
fc.write(ByteBuffer.wrap(("\n").getBytes()));
System.out.println(i);
}
} catch (Exception e) {
e.printStackTrace();
}
}
...我確實得到了很好的可中斷文件寫入線程。
添加回答
舉報