forked from Java2ArkTS/Java2ArkTS
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSimpleFuture.java
More file actions
49 lines (37 loc) · 1.21 KB
/
Copy pathSimpleFuture.java
File metadata and controls
49 lines (37 loc) · 1.21 KB
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
public class SimpleFuture {
private String result;
private boolean isDone;
public SimpleFuture() {
this.isDone = false;
}
// 设置任务结果,并唤醒等待的线程
public synchronized void setResult(String result) {
this.result = result;
this.isDone = true;
notifyAll(); // 唤醒所有等待的线程
}
// 获取任务结果,如果任务未完成,则等待
public synchronized String get() {
while (!isDone) {
}
return result;
}
// 检查任务是否完成
public synchronized boolean isDone() {
return isDone;
}
public static void main(String[] args) {
SimpleFuture future = new SimpleFuture();
// 启动一个线程来模拟异步任务
Thread asyncTask = new Thread(() -> {
// 模拟异步任务需要一些时间来完成
for(int i=0;i<1000;i++);
future.setResult("Task completed"); // 设置结果
});
asyncTask.start();
System.out.println("Doing something else...");
// 获取异步任务结果
String result = future.get();
System.out.println("Result: " + result);
}
}