import java.util.function.Consumer;
/**
* Future ->代表的是未来的一个凭据
* FutureTask ->将你的调用逻辑进行了隔离
* FutureService ->桥接 Future和 FutureTask
*/
public class SyncInvoker {
public static void main(String[] args) throws InterruptedException {
FutureService futureService = new FutureService();
//在此设计模式里FutureTask里编写的就是需要执行的任务
FutureTask<String> futureTask = new FutureTask<String>() {
@Override
public String call() {
try {
Thread.sleep(10000l);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "Hey,finish!!!!!!!";
}
};
//类比订蛋糕后,不是等一段时间我去打电话问蛋糕好没好,而是我留下联系方式,做好了让店家打电话给我
//此为优化,Consumer是java1.8的新接口
//如果没有做优化,在下面还要主动调用
Consumer<String> consumer = new Consumer<String>() {
@Override
public void accept(String s) {
System.out.println(s);
}
};
//如果没有做优化,在下面获取完submit返回的Future对象,还要调用Future的get方法
futureService.submit(futureTask, consumer);
System.out.println("===========");
System.out.println(" do other thing.");
Thread.sleep(1000);
System.out.println("===========");
}
}
public interface Future<T> {
T get() throws InterruptedException;
}
public class AsynFuture<T> implements Future<T> {
private volatile boolean done = false;
private T result;
public void done(T result) {
synchronized (this) {
this.result = result;
this.done = true;
this.notifyAll();
}
}
@Override
public T get() throws InterruptedException {
synchronized (this) {
while (!done) {
this.wait();
}
}
return result;
}
}
public interface FutureTask<T> {
T call();
}
- 连接任务和未来的Service(其实运行到这里是有两条线程)
public class FutureService {
//未优化
public <T> Future<T> submit(final FutureTask<T> task) {
AsynFuture<T> asynFuture = new AsynFuture<>();
new Thread(() -> {
T result = task.call();
asynFuture.done(result);
}).start();
return asynFuture;
}
//已优化
public <T> Future<T> submit(final FutureTask<T> task, final Consumer<T> consumer) {
AsynFuture<T> asynFuture = new AsynFuture<>();
new Thread(() -> {
T result = task.call();
asynFuture.done(result);
consumer.accept(result);
}).start();
return asynFuture;
}
}
网友评论