我的代码:
String[] torrentFiles = new File("/root/torrents/").list();
if(torrentFiles.length == 0 || torrentFiles == null)
{
System.exit(0);
}
ex = Executors.newFixedThreadPool(3);
for(String torrentFile : torrentFiles)
{
ex.submit(new DownloadTorrent("/root/torrents/" + torrentFile));
}
ex.shutdown();
try
{
ex.awaitTermination(30, TimeUnit.MINUTES);
}
catch(InterruptedException ex1)
{
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex1);
}
但有时 torrent 下载需要未知的时间值,而 «awaitTermination
» 无法正常工作。我需要在半小时后立即停止所有执行的线程,但据我所知,«awaitTermination
» 仅使用仅在循环或等待中工作的 interrupt()
方法。因此,如果这一刻发生,超时将不起作用。那么,如何呢?
最佳答案
永远无法保证立即终止线程,除非线程定期检查 isInterrupted() 标志(或正在等待可中断方法,即抛出 InterruptedException)。
当工作线程定期检查 isInterrupted() 时,请考虑以某种方式实现工作线程。这可能是这样的:
public void run() {
byte[] data;
do {
data = receiveDataChunk(timeout);
processData(data);
} while(!isInterrupted() && data != null);
}
关于Java:强制停止 ExecutorService 线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5946562/