多线程之实现Calladle接口
需要使用线程池,ExecutorService的submit执行
public class CallableClient implements Callable<Boolean> {
<pre><code>private String name;
private String url;
private WebDownload webDownload;
public CallableClient(String name, String url) {
this.name = name;
this.url = url;
webDownload = new WebDownload();
}
@Override
public Boolean call() throws Exception {
webDownload.download(url,name);
System.out.println(Thread.currentThread().getName() + "下载完毕");
return true;
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
CallableClient c1 = new CallableClient("1.jpg","<https://scpic.chinaz.net/files/pic/pic9/202106/apic33157.jpg>");
CallableClient c2 = new CallableClient("2.jpg","<https://scpic.chinaz.net/files/pic/pic9/202106/bpic23398.jpg>");
CallableClient c3 = new CallableClient("3.jpg","<https://scpic.chinaz.net/files/pic/pic9/201907/hpic1227.jpg>");
ExecutorService executor = Executors.newFixedThreadPool(10);
Future<Boolean> f1 = executor.submit(c1);
Future<Boolean> f2 = executor.submit(c2);
Future<Boolean> f3 = executor.submit(c3);
f1.get();
f2.get();
f3.get();
executor.shutdownNow();
}
}
class WebDownload { public boolean download(String url,String name) { try { FileUtils.copyURLToFile(new URL(url),new File(name)); } catch (IOException e) { e.printStackTrace(); System.out.println("下载异常"); return false; } return true; } }
评论区