多线程:实现Callable接口
生活随笔
收集整理的這篇文章主要介紹了
多线程:实现Callable接口
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
package com.wuming.demo02;import com.sun.org.apache.xpath.internal.operations.Bool;
import org.apache.commons.io.FileUtils;import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.concurrent.*;//練習Thread,實現多線程同步下載圖片
//線程創建方式三:實現callable接口
public class TestCallable implements Callable<Boolean> {private String url;//網絡圖片地址private String name;//保存的文件名public TestCallable(String url,String name){this.url=url;this.name=name;}//下載圖片線程的執行體@Overridepublic Boolean call() {webDown_two webDown = new webDown_two();webDown.downloader(url,name);System.out.println("下載的文件名為:"+name);return true;}public static void main(String[] args) throws ExecutionException, InterruptedException {//ctrl+d快速復制三行TestCallable t1 = new TestCallable("https://lmg.jj20.com/up/allimg/tp09/210611094Q512b-0-lp.jpg","1.jpg");TestCallable t2 = new TestCallable("https://lmg.jj20.com/up/allimg/tp09/210611094Q512b-0-lp.jpg","2.jpg");TestCallable t3 = new TestCallable("https://lmg.jj20.com/up/allimg/tp09/210611094Q512b-0-lp.jpg","3.jpg");//多線程同時下載多張圖片,每次執行結果不一樣,占cpu多就先執行//創建執行任務: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();System.out.println(rs1);System.out.println(rs2);System.out.println(rs3);//關閉ser.shutdownNow();}
}//下載器
class webDown_two{//下載方法public void downloader(String url,String name){try {FileUtils.copyURLToFile(new URL(url),new File(name));} catch (IOException e) {e.printStackTrace();System.out.println("IO異常,downloader方法出現問題");}}
}
下載的文件名為:3.jpg
下載的文件名為:1.jpg
下載的文件名為:2.jpg
true
true
true
?
總結
以上是生活随笔為你收集整理的多线程:实现Callable接口的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: C语言 const 修饰变量 - C语言
- 下一篇: C语言 memcpy和memcpy_s区