线程的创建之实现Callable接口
1. 过程
- 实现Callable接口,需要返回值类型。
- 重写call方法,需要抛出异常。
- 创建目标对象
- 创建执行任务:
ExecutorService ser = Executors.newFixedThreadPool(1);
。
- 提交实行:
Future<Boolean> result1 = ser.submit(t1);
。
- 获取结果:
boolean r1 = result1.get()
。
- 关闭服务:
ser.shutdownNow();
。
2. 使用
public class Demo6 implements Callable<Boolean> {
private String url;
private String name;
public Demo6(String url, String name) {
this.url = url;
this.name = name;
}
@Override
public Boolean call() {
new WebDownloader1().downloader(url, name);
System.out.println("下载的文件名为" + name);
return true;
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
Demo6 t1 = new Demo6("https://cdn.jsdelivr.net/gh/rootwhois/oss@main/uPic/image-20210820235038265.png", "1.png");
Demo6 t2 = new Demo6("https://cdn.jsdelivr.net/gh/rootwhois/oss@main/uPic/image-20210820235038265.png", "2.png");
Demo6 t3 = new Demo6("https://cdn.jsdelivr.net/gh/rootwhois/oss@main/uPic/image-20210820235038265.png", "3.png");
ExecutorService executorService = Executors.newFixedThreadPool(3);
Future<Boolean> submit = executorService.submit(t1);
Future<Boolean> submit1 = executorService.submit(t2);
Future<Boolean> submit2 = executorService.submit(t3);
Boolean rs1 = submit.get();