hooyantsing's Blog

8_实现Callable接口

字数统计: 477阅读时长: 2 min
2020/08/20

8 实现Callable接口

狂神说Java 多线程详解

除继承 Thread 和 实现 Runnable 之外,第三种方式:实现 Callable 接口来创建线程

实现 Callable 接口(了解即可)

  1. 实现Callable接口,需要返回值类型(泛型的类型和call方法返回类型一致)
  2. 重写call方法,需要抛出异常(call方法相当于run方法)
  3. 创建目标对象
  4. 创建执行服务:ExecutorService ser = Executors.newFixedThreadPool(3); (创建线程池)
  5. 提交执行:Future r1 = ser.submit(t1); (将任务分配给线程池内某个线程)
  6. 获取结果:boolean rs1 = r1.get();
  7. 关闭服务:ser.shutdownNow(); (关闭线程池)

    案例

使用Callable将图片下载改造。

[4 网图下载]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package demo2;

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.concurrent.*;

public class TestCallable implements Callable<Boolean> {
private String url;
private String name;

public TestCallable(String url, String name) {
this.url = url;
this.name = name;
}

@Override
public Boolean call() {
new WebDownloader().downloader(url,name);
System.out.println("下载了文件名:" + name);
return true;
}

public static void main(String[] args) throws ExecutionException, InterruptedException {
TestCallable t1 = new TestCallable("https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=151472226,3497652000&fm=26&gp=0.jpg","1.jpg");
TestCallable t2 = new TestCallable("https://ss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=3367568658,3302321631&fm=26&gp=0.jpg","2.jpg");
TestCallable t3 = new TestCallable("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1597910837734&di=c04bbb658aae00cadceece45f98c7bf6&imgtype=0&src=http%3A%2F%2F01.imgmini.eastday.com%2Fmobile%2F20170709%2F20170709004858_f316b2aee3d7cc6a0408be4dd5c633e3_1.jpeg","3.jpg");

// Callable 四步骤启动线程
// 创建执行服务
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();
// 关闭服务
ser.shutdownNow();
}
}

class WebDownloader {
// 下载方法
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 异常");
}
}
}
CATALOG
  1. 1. 8 实现Callable接口
    1. 1.0.1. 实现 Callable 接口(了解即可)
    2. 1.0.2. 案例