这种创建线程的方法,只做了解
分为以下几步:
第一步: 实现Callable接口,需要返回值类型
第二步: 重写call方法,需要抛出异常
第三步: 创建目标对象
第四步: 创建执行服务
ExecutorService ser = Executors.newFixedThreadPool(1);
第五步:提交执行
Future<Boolean> result1 = ser.submit(t1);
第六步:获取结果
boolean r1 = result1.get()
第七步:关闭服务
ser.shutdownNow()
下面看代码:
package duoxiancheng;
import java.util.concurrent.*;
//线程创建方式三,实现callable接口
public class TestCallable implements Callable<Boolean> {
private String url; //图片的url
private String name; //图片的名字
public TestCallable(String url, String name) {
this.url = url;
this.name = name;
}
@Override
public Boolean call() {
WebDownloader webDownloader = new WebDownloader();
webDownloader.downloader(url, name);
System.out.println("下载了文件名为: " + name);
return true;
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
TestCallable t1 = new TestCallable("https://csdnimg.cn/release/blogv2/dist/pc/img/tobarCollectionActive.png", "1. png");
TestCallable t2 = new TestCallable("https://csdnimg.cn/release/blogv2/dist/pc/img/tobarThumbUpactive.png", "2.png");
TestCallable t3 = new TestCallable("https://csdnimg.cn/release/blogv2/dist/pc/img/tobarThumbUp.png", "3.png");
//创建执行服务
ExecutorService executorService = Executors.newFixedThreadPool(3);
//提交执行
Future<Boolean> r1 = executorService.submit(t1);
Future<Boolean> r2 = executorService.submit(t2);
Future<Boolean> r3 = executorService.submit(t3);
boolean result1 = r1.get();
boolean result2 = r2.get();
boolean result3 = r3.get();
System.out.println("result1 = " + result1);
System.out.println("result2 = " + result2);
System.out.println("result3 = " + result3);
executorService.shutdown();
}
}
使用callable的好处:
第一:可以定义返回值
第二:可以抛出异常
实现方式也复杂了很多~