创建线程还有第三种方式:那就是实现Callable接口
与其他两种方式(继承Thread类和实现Runnable接口)略有不同:实现Callable接口,重写里面的call方法,可以有返回值(自己设置)。需要抛出异常
代码如下
package com.bes.mybatis_plus.Test1;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.concurrent.*;
//实现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;
}
/**
* 这里执行的是call方法,不是run方法,这是一个区别,且需要返回值,与类的返回值一样
* @return
*/
@Override
public Boolean call() {
//run方法线程体
WebDownLoader1 webDownLoader = new WebDownLoader1();
webDownLoader.downloader(url, name);
System.out.println("下载了图片: " + name);
//这里先写死,用不着,返回true,
return true;
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
//创建三个线程
TestCallable t1 = new TestCallable
("\thttps://img2020.cnblogs.com/blog/2363175/202106/2363175-20210615223436333-1586269648.png", "1.png");
TestCallable t2 = new TestCallable
("https://img2020.cnblogs.com/blog/2363175/202106/2363175-20210615223513504-596161120.png", "2.png");
TestCallable t3 = new TestCallable
("https://img2020.cnblogs.com/blog/2363175/202106/2363175-20210615223623978-1534224149.png", "3.png");
//平常方式启动
// t1.start();
// t2.start();
// t3.start();
//创建执行服务,创建容量为3的线程池
ExecutorService ser = Executors.newFixedThreadPool(3);
//提交执行,把三个线程提交执行
Future<Boolean> result1 = ser.submit(t1);
Future<Boolean> result2 = ser.submit(t2);
Future<Boolean> result3 = ser.submit(t3);
//获取结果,返回值
boolean rs1 = result1.get();
boolean rs2 = result2.get();
boolean rs3 = result3.get();
//关闭服务
ser.shutdown();
}
}
//下载器
class WebDownLoader1 {
//下载方法
public void downloader(String url, String name) {
try {
//从制定url下载文件的工具类,后面跟下载之后的名字
FileUtils.copyURLToFile(new URL(url), new File(name));
} catch (IOException e) {
e.printStackTrace();
System.out.println("下载失败,downLoader方法出现问题咯");
}
}
}
注:需要导入commons-io-2.4.jar包,使用里面的文件下载器,才可以使用里面的包,实现下载文件哦,具体方法:
1、直接百度搜commons-io下载
2、用我的百度网盘下载地址:百度网盘资源,提取码:1111
3、另一个直接下载地址(可能会失效):直接下载