1. 程式人生 > 其它 >多執行緒-實現Callable介面-修改下載圖片的案例

多執行緒-實現Callable介面-修改下載圖片的案例

1.實現callable介面,需要返回值型別
2.重寫call方法,需要丟擲異常
3.建立目標物件
4.建立執行服務:ExecutorService ser=Exectutors.newFixedThreadPool();
5.提交執行:Future<Boolean> result1=ser.submit(t1);
6.獲取結果:boolean r1=result1.get();
7.關閉服務:ser.shutdownNow();

  

import java.util.Scanner;
import org.apache.commons.io.FileUtils;
import java.net.URL;
//執行緒建立方式三,實現Callable /* Callable好處: 1.可以定義返回值 2.可以丟擲異常 */ public class Main implements Callable<boolean> {//要有返回值型別 //建立變數 private String url; private String name; public Main(){} public Main(String url,String name){ this.url=url; this.name=name; }
//執行緒體:下載圖片執行緒的執行體 public boolean call(){ WebDownloader webDownloader=new WebDownloader();//建立下載器物件 //呼叫下載器中的方法 webDownloader.downloader(url,name); System.out.println("下載了檔名為:"+url); return true;//無論怎麼樣,我們執行這就方法,返回一個真 } public static void main(String []args){ Main t1
=new Main("https://img01.sogoucdn.com/app/a/100520021/3b453574cfbfd216bc9e22b7aedb75a3","1.jpg"); Main t2=new Main("https://img01.sogoucdn.com/app/a/100520021/3b453574cfbfd216bc9e22b7aedb75a3","2.jpg"); Main t3=new Main("https://img01.sogoucdn.com/app/a/100520021/3b453574cfbfd216bc9e22b7aedb75a3","3.jpg"); //建立執行服務: ExecutorService ser=Exectutors.newFixedThreadPool(3);//建立3個池子 //把執行緒,提交執行: Future<Boolean> result1=ser.submit(t1); Future<Boolean> result2=ser.submit(t2); Future<Boolean> result3=ser.submit(t3); //獲取結果:會有異常丟擲就行 boolean r1=result1.get(); boolean r2=result2.get(); boolean r3=result3.get(); //列印返回值 System.out.println(r1); System.out.println(r2); System.out.println(r3); //關閉服務: ser.shutdownNow(); } } //下載器 class WebDownloader{ //下載方法 public void downloader(String url,String name){ try{ //copyURLToFile:把網上的檔案地址,變成一個檔案,new URL(url):新增一個網路路徑,new File(name):新增一個檔案路徑 FileUtils.copyURLToFile(new URL(url),new File(name)); }catch(IOException e){ e.printStackTrace(); System.out.println("IO異常,downloader出現問題"); } } }