Java8 - 自定义实现体会CompletableFuture的原理
【摘要】
文章目录
Code
Code
Future 接口 的局限性有很多,其中一个就是需要主动的去询问是否完成,如果等子线程的任务完成以后,通知我,那岂不是更好?
public cla...
Code
Future 接口 的局限性有很多,其中一个就是需要主动的去询问是否完成,如果等子线程的任务完成以后,通知我,那岂不是更好?
public class FutureInAction3 {
public static void main(String[] args) {
Future<String> future = invoke(() -> {
try {
Thread.sleep(10000L);
return "I am Finished.";
} catch (InterruptedException e) {
return "I am Error";
}
});
future.setCompletable(new Completable<String>() {
@Override
public void complete(String s) {
System.out.println("complete called ---- " + s);
}
@Override
public void exception(Throwable cause) {
System.out.println("error");
cause.printStackTrace();
}
});
System.out.println("....do something else .....");
System.out.println("try to get result ->" + future.get());
}
private static <T> Future<T> invoke(Callable<T> callable) {
AtomicReference<T> result = new AtomicReference<>();
AtomicBoolean finished = new AtomicBoolean(false);
Future<T> future = new Future<T>() {
private Completable<T> completable;
@Override
public T get() {
return result.get();
}
@Override
public boolean isDone() {
return finished.get();
}
// 设置完成
@Override
public void setCompletable(Completable<T> completable) {
this.completable = completable;
}
// 获取
@Override
public Completable<T> getCompletable() {
return completable;
}
};
Thread t = new Thread(() -> {
try {
T value = callable.action();
result.set(value);
finished.set(true);
if (future.getCompletable() != null)
future.getCompletable().complete(value);
} catch (Throwable cause) {
if (future.getCompletable() != null)
future.getCompletable().exception(cause);
}
});
t.start();
return future;
}
private interface Future<T> {
T get();
boolean isDone();
// 1
void setCompletable(Completable<T> completable);
// 2
Completable<T> getCompletable();
}
private interface Callable<T> {
T action();
}
// 回调接口
private interface Completable<T> {
void complete(T t);
void exception(Throwable cause);
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76
- 77
- 78
- 79
- 80
- 81
- 82
- 83
- 84
- 85
- 86
- 87
- 88
- 89
- 90
- 91
- 92
- 93
- 94
- 95
- 96
- 97
- 98
- 99
- 100
- 101
- 102
- 103
- 104
- 105
- 106

文章来源: artisan.blog.csdn.net,作者:小小工匠,版权归原作者所有,如需转载,请联系作者。
原文链接:artisan.blog.csdn.net/article/details/115450097
【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)