Python 官方文档:入门教程 => 点击学习
目录Future -> 代表的是未来的一个凭据AsynFuture -> Future具体实现类FutureService -> 桥接Future和FutureTa
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 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;
}
}
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设计模式的文章就介绍到这了,更多相关Java多线程 Future内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!
--结束END--
本文标题: Java多线程之Future设计模式
本文链接: https://www.lsjlt.com/news/155757.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-03-01
2024-03-01
2024-03-01
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0