Callable接口实现
Callable接口实现
之前学过callable, 这次再学些不一样的东西
Callable vs. Runnable
- Callable 接口有返回值, Runnable 接口没有返回值
- Callable 接口可以抛出异常, Runnable 接口不能抛出异常
- 一个重写call方法,一个重写run方法
- Callable通过Thread调用需要通过FutureTask,Runnable可以直接调用
- Callable会有缓存
代码
Runnable
package com.example.juc;
public class TestRunnable {
public static void main(String[] args) {
MyThreadRun myThreadRun = new MyThreadRun();
new Thread(myThreadRun).start();
new Thread(myThreadRun).start();
}
}
class MyThreadRun implements Runnable {
@Override
public void run() {
System.out.println("Run");
}
}
Run
Run
Callable
package com.example.juc;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
public class TestCallable {
public static void main(String[] args) throws ExecutionException, InterruptedException {
MyThreadCall myThreadCall = new MyThreadCall();
FutureTask<Integer> integerFutureTask = new FutureTask<>(myThreadCall);
new Thread(integerFutureTask).start();
new Thread(integerFutureTask).start();
Integer integer = integerFutureTask.get();
System.out.println(integer);
}
}
class MyThreadCall implements Callable<Integer> {
@Override
public Integer call() {
System.out.println("Call");
return 1024;
}
}
Call
1024