Future 接口:
public interface Future<T> {
T get() throws InterruptedException;
boolean isDone();
void Cancel();
boolean isCancel();
}
FutureTask类:
public class FutureTask<T> implements Future<T> {
private volatile boolean done = false;
private boolean cancel = false;
private T result;
@Override
public T get() throws InterruptedException {
synchronized (this){ //1.
while (!done){
this.wait();
}
return result;
}
}
protected void done(T result){
synchronized (this){ //2.
this.result = result;
this.done = true;
notifyAll();
}
}
@Override
public boolean isDone() {
return done;
}
@Override
public boolean isCancel() {
return cancel;
}
@Override
public void Cancel() {
}
}
1 处 2 处加 synchronized 的原因:如果不加 synchronized,尝试获取结果时,但此时还没返回结果,只能 while 自旋等待,这不耗费资源吗?加上 synchronized,没结果就释放资源挂起,等待有了结果,再去唤醒。
FutureService类:
public class FutureService<T> {
public Future submit(Callable<T> callable) {
final FutureTask<T> task = new FutureTask();
new Thread(()->{
T result = null;
try {
result = callable.call();
} catch (Exception e) {
e.printStackTrace();
}
task.done(result);
}).start();
return task;
}
}
测试类:
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Client {
public static void main(String[] args) throws Exception {
FutureService service = new FutureService();
Future<String> future = service.submit(new Callable() {
@Override
public String call() throws InterruptedException {
System.out.println("call start");
Thread.sleep(5000);
return "call end";
}
});
Thread.sleep(1000);
System.out.println("Thread main do other things");
System.out.println(future.isDone());
System.out.println(future.get());
}
}