当前位置: 代码迷 >> 综合 >> 从头认识java-17.6 Callable、Future和FutureTask
  详细解决方案

从头认识java-17.6 Callable、Future和FutureTask

热度:37   发布时间:2023-12-10 03:44:18.0

这一章节我们来讨论一下Callable、Future和FutureTask的用法与关系。

1.关系

(1)Callable是Runnable的封装的异步运算任务

(2)Future用来保存Callable异步运算的结果

(3)FutureTask封装Future的实体类

 

2.Future

我们在这里详细介绍一下Future,因为它比较复杂,首先看看他的源代码:

public interface Future<V> { 
boolean cancel(boolean mayInterruptIfRunning); 
boolean isCancelled(); 
boolean isDone(); 
V get() throws InterruptedException, ExecutionException; 
V get(long timeout, TimeUnit unit) 
throws InterruptedException, ExecutionException, TimeoutException; 
} 


它里面包含了几个方法

get:得到结果

get(timeout,unit)计算是否超时得到结果

cancle:取消任务

isDone、isCancle:判断任务状态

 

3.例子:

Callable和FutureTask

package com.ray.ch17;
import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
public class Test {
public static void main(String[] args) throws InterruptedException,
ExecutionException {
Callable<Integer> callable = new MyCall();
FutureTask<Integer> futureTask = new FutureTask<Integer>(callable);
Thread thread = new Thread(futureTask);
thread.start();
Thread.sleep(100);
if (!futureTask.isDone()) {
System.out.println(futureTask.get());
}
if (!futureTask.isCancelled()) {
futureTask.cancel(true);
System.out.println("cancelled");
}
}
}
class MyCall implements Callable<Integer> {
@Override
public Integer call() throws Exception {
System.out.println("doing something...");
Thread.sleep(1000);
return new Random().nextInt(50);
}
}


我们只需要将上面main方法里面的两个if互换就可以得出不同的结果。

 

Callable和Future

 

package com.ray.ch17;
import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class Test {
public static void main(String[] args) throws InterruptedException,
ExecutionException {
ExecutorService executors = Executors.newCachedThreadPool();
Callable<Integer> callable = new MyCall();
Future<Integer> future = executors.submit(callable);
System.out.println(future.get());
}
}
class MyCall implements Callable<Integer> {
@Override
public Integer call() throws Exception {
System.out.println("doing something...");
Thread.sleep(1000);
return new Random().nextInt(50);
}
}


 

 

总结:这一章节主要介绍了Callable、Future和FutureTask的用法与关系。

 

 

这一章节就到这里,谢谢。

-----------------------------------

目录

 

  相关解决方案