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