Skip to content

Commit aced942

Browse files
authored
Create AsyncFunction.java
1 parent 3692e97 commit aced942

1 file changed

Lines changed: 66 additions & 0 deletions

File tree

‎AsyncFunction.java‎

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
import java.util.concurrent.Callable;
2+
public class AsyncFunction {
3+
public enum Status{
4+
NOT_STARTED,
5+
RUNNING,
6+
DONE,
7+
INTERRUPT
8+
}
9+
private Callable<?> func;
10+
private Object result;
11+
private boolean await;
12+
private Thread thread;
13+
private Status status;
14+
public AsyncFunction(Callable<?> func, boolean await) {
15+
this.func = func;
16+
this.await = await;
17+
this.result = null;
18+
this.status = Status.NOT_STARTED;
19+
}
20+
21+
public Object run(){
22+
Runnable task = ()->{
23+
try {
24+
this.result = func.call();
25+
this.status = Status.DONE;
26+
} catch (Exception e) {
27+
throw new RuntimeException(e);
28+
}
29+
};
30+
this.thread = new Thread(task);
31+
this.thread.setDaemon(true);
32+
thread.start();
33+
this.status = Status.RUNNING;
34+
if(await){
35+
try {
36+
thread.join();
37+
} catch (InterruptedException e) {
38+
throw new RuntimeException(e);
39+
}
40+
}
41+
return this.result;
42+
}
43+
public void interrupt(){
44+
this.thread.interrupt();
45+
this.status = Status.INTERRUPT;
46+
}
47+
public Object getResult(){
48+
return this.result;
49+
}
50+
public Status getStatus(){
51+
return this.status;
52+
}
53+
54+
public boolean isAwait() {
55+
return await;
56+
}
57+
58+
public void setAwait(boolean await) {
59+
if (this.status == Status.NOT_STARTED) {
60+
this.await = await;
61+
return;
62+
}
63+
throw new RuntimeException("Function already started!");
64+
}
65+
}
66+

0 commit comments

Comments
 (0)