1.定义Task类,实现了Callable接口
public class Task implements Callable<Long> {
private long num;
public Task(Long num){
this.num = num;
}
public Long call() throws Exception {
long r = 0;
for (long i = 0; i < this.num; i++) {
r = r+i;
}
System.out.println(r);
return r;
}
2.开一个线程执行call方法
Callable<Long> callable = new Task(123L);
Thread thread = new Thread(callable);//编译错误,thread只能接受runnerable接口
thread.start();
3.用一个Adapter,把这个Callable
接口“变成”Runnable
接口
Callable<Long> callable = new Task(123L);
Thread thread = new Thread(new RunnableAdapter(callable));
thread.start();
4.定义RunnableAdapter适配器
public class RunnableAdapter implements Runnable{
public Callable<Long> callable;
public RunnableAdapter(Callable<Long> callable){
this.callable = callable;
}
public void run() {
try {
callable.call();
} catch (Exception e) {
e.printStackTrace();
}
}
}
编写一个Adapter的步骤如下:
- 实现目标接口,这里是
Runnable
; - 内部持有一个待转换接口的引用,这里是通过字段持有
Callable
接口; - 在目标接口的实现方法内部,调用待转换接口的方法。