Cla*_*ark 5 java multithreading executorservice
我的代码:
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);
}
Run Code Online (Sandbox Code Playgroud)
但有时洪流下载需要未知的时间价值,« awaitTermination»不能按我的意愿工作.我需要在半小时后立即停止所有执行的线程,但据我所知« awaitTermination»只使用interrupt()仅在循环或等待中工作的方法.如果这一刻发生,超时不起作用.那么,怎么样?
除非线程定期检查isInterrupted()标志(或正在等待可中断的方法,即抛出InterruptedException),否则永远不会保证即时线程终止.
当他们定期检查isInterrupted()时,请考虑以方式实现工作线程.这可能是这样的:
public void run() {
byte[] data;
do {
data = receiveDataChunk(timeout);
processData(data);
} while(!isInterrupted() && data != null);
}
Run Code Online (Sandbox Code Playgroud)
小智 6
ExecutorService.shutdownNow() 将尝试停止所有正在执行的线程..
这是javadoc的引用
List<Runnable> shutdownNow()尝试停止所有正在执行的任务,停止等待任务的处理,并返回等待执行的任务列表.
除尽力尝试停止处理主动执行任务之外,没有任何保证.例如,典型的实现将通过Thread.interrupt()取消,因此如果任何任务屏蔽或无法响应中断,它们可能永远不会终止.
由于下载torrent可能涉及阻止IO操作,因此简单地调用cancel()/ shutdownNow()将是不够的,因为阻止IO操作不能保证在它们各自的线程被中断时终止.
您还需要关闭底层套接字以取消阻塞IO,请参阅如何立即终止套接字IO操作上的线程阻塞?.
| 归档时间: |
|
| 查看次数: |
30296 次 |
| 最近记录: |