两者的区别:Runnable接口不能有返回值,且不能抛出异常,而Callable接口可以
Runnable接口使用方式:
Runnable runnable = new Runnable() {
@Override
public void run() {
System.out.println(2222);
}
};
new Thread(runnable).start();
Callable接口使用方式:
Callable<Integer> callable = new Callable<Integer>() {
@Override
public Integer call() throws Exception {
Integer result = new Random().nextInt(100);
System.out.println(
Thread.currentThread().getName() + " " + result);
Thread.sleep(1000);
return result;
}
};
FutureTask<Integer> ft1 = new FutureTask<>(callable);
FutureTask<Integer> ft2 = new FutureTask<>(callable);
// 下面的a和b线程只有一个会运行,c线程会正常运行
new Thread(ft1, "a").start();
new Thread(ft1, "b").start();
new Thread(ft2, "c").start();
// ft1.get()方法会阻塞当前线程,直到有返回值为止
System.out.println(ft1.get());
System.out.println(ft2.get());