Skip to content

Commit c65639e

Browse files
committed
future to callback
1 parent 3c6f3be commit c65639e

File tree

3 files changed

+64
-2
lines changed

3 files changed

+64
-2
lines changed
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
package concurrency.future;
2+
3+
public class CallbackEx {
4+
5+
interface Callback {
6+
void onSuccess();
7+
}
8+
9+
public static void main(String[] args) {
10+
11+
12+
}
13+
14+
}

src/main/java/concurrency/future/FutureEx.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -29,10 +29,10 @@ public static void main(String[] args) throws InterruptedException, ExecutionExc
2929

3030
log.debug("Is the async task done? " + future.isDone());
3131
log.debug("Processing the other task");
32-
Thread.sleep(2000);
32+
Thread.sleep(1000);
3333

3434
log.debug("Is the async task done? " + future.isDone());
35-
log.debug("The async result is " + future.get()); // blocking, wait the async result.
35+
System.out.println("The async result is " + future.get()); // blocking, wait the async result.
3636
log.debug("Exit " + (System.currentTimeMillis() - startTime));
3737
}
3838
}
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
package concurrency.future;
2+
3+
import java.util.concurrent.ExecutionException;
4+
import java.util.concurrent.ExecutorService;
5+
import java.util.concurrent.Executors;
6+
import java.util.concurrent.Future;
7+
import java.util.concurrent.FutureTask;
8+
import lombok.extern.slf4j.Slf4j;
9+
10+
@Slf4j
11+
public class FutureTaskEx {
12+
13+
public static void main(String[] args) throws InterruptedException, ExecutionException {
14+
log.debug("Enter");
15+
final ExecutorService executorService = Executors.newCachedThreadPool();
16+
17+
final long startTime = System.currentTimeMillis();
18+
FutureTask<String> future = new FutureTask<>(
19+
() -> {
20+
log.debug("Processing task asynchronously");
21+
try {
22+
Thread.sleep(2000);
23+
} catch (InterruptedException e) {
24+
throw new RuntimeException(e);
25+
}
26+
27+
return "AsyncResult";
28+
}
29+
) {
30+
@Override
31+
protected void done() {
32+
try {
33+
System.out.println("The async result is " + get());
34+
} catch (InterruptedException | ExecutionException e) {
35+
throw new RuntimeException(e);
36+
}
37+
}
38+
};
39+
40+
executorService.execute(future);
41+
executorService.shutdown();
42+
43+
log.debug("Is the async task done? " + future.isDone());
44+
log.debug("Processing the other task");
45+
Thread.sleep(1000);
46+
log.debug("Exit " + (System.currentTimeMillis() - startTime));
47+
}
48+
}

0 commit comments

Comments
 (0)