java 设计模式 future_Java多线程15 Future设计模式

Future -> 代表的是未来的一个凭据

public interface Future {

T get() throws InterruptedException;

}

AsynFuture -> Future具体实现类

public class AsynFuture implements Future {

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;

}

}

FutureService -> 桥接Future和FutureTask

public class FutureService {

/**

* 需进程等待

*/

public Future submit(final FutureTask task) {

AsynFuture asynFuture = new AsynFuture<>();

new Thread(() -> {

T result = task.call();

asynFuture.done(result);

}).start();

return asynFuture;

}

/**

* 运行完 自动回调

* 无需进程等待

*/

public Future submit(final FutureTask task, final Consumer consumer) {

AsynFuture asynFuture = new AsynFuture<>();

new Thread(() -> {

T result = task.call();

asynFuture.done(result);

consumer.accept(result);

}).start();

return asynFuture;

}

}

FutureTask -> 将你的调用逻辑进行了隔离

public interface FutureTask {

T call();

}

需要时回调

/**

* Future -> 代表的是未来的一个凭据

* FutureTask -> 将你的调用逻辑进行了隔离

* FutureService -> 桥接Future和FutureTask

*/

public class SyncInvoker {

public static void main(String[] args) throws InterruptedException {

FutureService futureService = new FutureService();

Future future = futureService.submit(() -> {

try {

Thread.sleep(10001);

} catch (InterruptedException e) {

e.printStackTrace();

}

return "FINISH";

});

System.out.println("==============");

System.out.println("do other thing.");

Thread.sleep(1000);

System.out.println("==============");

/**

* 调用也形成了阻塞

*/

System.out.println(future.get());

}

}

运行

==============

do other thing.

==============

FINISH

运行完自动回调

//**

* Future -> 代表的是未来的一个凭据

* FutureTask -> 将你的调用逻辑进行了隔离

* FutureService -> 桥接Future和FutureTask

*/

public class SyncInvoker {

public static void main(String[] args) throws InterruptedException {

FutureService futureService = new FutureService();

futureService.submit(() -> {

try {

Thread.sleep(10001);

} catch (InterruptedException e) {

e.printStackTrace();

}

return "FINISH";

},System.out::println);

System.out.println("==============");

System.out.println("do other thing.");

Thread.sleep(1000);

System.out.println("==============");

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值