你真的想使用ExperatorService而不是单个线程,它更干净,可能更高性能,并且将使您能够在以后更轻松地更改内容(线程计数,线程名称等):
ExecutorService pool = Executors.newFixedThreadPool(10);
for (String name : fileNames) {
pool.submit(new DownloadTask(name, toPath));
}
pool.shutdown();
pool.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS);
// all tasks have now finished (unless an exception is thrown above)
在你的班级中的其他地方定义了实际的工作马:DownloadTask
private static class DownloadTask implements Runnable {
private String name;
private final String toPath;
public DownloadTask(String name, String toPath) {
this.name = name;
this.toPath = toPath;
}
@Override
public void run() {
// surround with try-catch if downloadFile() throws something
downloadFile(name, toPath);
}
}
该方法有一个非常令人困惑的名称,因为它“将允许以前提交的任务在终止之前执行”。 声明您需要处理的。shutdown()
awaitTermination()
InterruptedException