java如何使用中断通道下载文件?(NIO)
当我接到来电时,我必须立即中断长时间运行的线程。我想用线。中断()方法来执行此操作
参考资料说:
Threads blocked in an I/O operation of an InterruptibleChannel will
have their interrupt status set and receive an ClosedByInterruptException.
Also, the channel will be closed.
在我的线程中,我正在通过HTTP下载一个文件,所以我想使用InterruptableChannel来立即停止下载。你能给我一些源代码,如何使用中断频道下载文件吗
这个解决方案不适合我,因为线程。中断()不中断阻塞IO:
while ((length = httpIn.read(buffer)) > 0) {
if(Thread.interrupted())
....
else
{
fileOut.write(buffer, 0, length);
fileSize += length;
}
}
# 1 楼答案
中断执行I/O时被阻塞的线程的一种常用方法是关闭通道。例如,如果一个线程在套接字上的read()操作中被阻塞,那么想要中断它的线程可以关闭套接字。 不确定这种方法是否对您有用,但它是一种通用的解决方案,有时会被使用