Java多线程之Future设计模式

网友投稿 283 2022-09-19


Java多线程之Future设计模式

目录Future -> 代表的是未来的一个凭据AsynFuture -> Future具体实现类FutureService -> 桥接Future和FutureTaskFutureTask -> 将你的调用逻辑进行了隔离

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

public interface Future {

T get() throws InterruptedException;

}

AsynFuture -> Future具体实现CCjdepGaW类

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();

futureServiCCjdepGaWce.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("==============");

}

}


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:分享6个网络延迟测试工具,都是老网工的必备好物(手机网络延迟测试工具)
下一篇:关于路由重分发,只用一篇文章就能教会你(路由引入与路由重发布)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~