这篇文章将为大家详细讲解有关Java多线程中Future设计模式怎么用,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。
Future -> 代表的是未来的一个凭据
public interface Future<T> { T get() throws InterruptedException;}
AsynFuture -> Future具体实现类
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; }}
FutureService -> 桥接Future和FutureTask
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; }}
FutureTask -> 将你的调用逻辑进行了隔离
public interface FutureTask<T> { T call();}
需要时回调:
public class SyncInvoker { public static void main(String[] args) throws InterruptedException { FutureService futureService = new FutureService(); Future<String> 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
运行完自动回调:
/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("=============="); }}
关于“Java多线程中Future设计模式怎么用”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,使各位可以学到更多知识,如果觉得文章不错,请把它分享出去让更多的人看到。