實現Callable介面
阿新 • • 發佈:2021-07-08
多執行緒下載圖片
package test2; import org.apache.commons.io.FileUtils; import java.io.File; import java.io.IOException; import java.net.URL; import java.util.Collection; import java.util.List; import java.util.concurrent.*; public class TestCallable implements Callable<Boolean>{ private String url; private String filename; public TestCallable(String url,String filename){ this.url=url; this.filename=filename; } @Override public Boolean call() { WebDownloader webDownloader=new WebDownloader(); webDownloader.downloader(url,filename); System.out.println("圖片下載結束名字為"+filename); return true; } public static void main(String[] args) throws ExecutionException, InterruptedException { TestCallable t1=new TestCallable("http://www.whxzn.com/images/banner/shouhou.jpg","1.jpg"); TestCallable t2=new TestCallable("http://www.whxzn.com/images/faq/1.jpg","2.jpg"); TestCallable t3=new TestCallable("http://www.whxzn.com/images/faq/3.jpg","3.jpg"); //建立執行服務 ExecutorService ser=Executors.newFixedThreadPool(3); //提交執行 Future<Boolean> r1= ser.submit(t1); Future<Boolean> r2= ser.submit(t2); Future<Boolean> r3= ser.submit(t3); //獲取結果 Boolean rs1 = r1.get(); Boolean rs2=r2.get(); Boolean rs3=r3.get(); //關閉服務 ser.shutdownNow(); } } //下載器 class WebDownloader{ //下載方法 public void downloader(String url,String filename){ try { FileUtils.copyURLToFile(new URL(url),new File(filename)); } catch (IOException e) { e.printStackTrace(); System.out.println("io異常"); } } }