forked from examplehub/Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCallableExampleTest.java
More file actions
49 lines (42 loc) · 1.33 KB
/
CallableExampleTest.java
File metadata and controls
49 lines (42 loc) · 1.33 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
package com.examplehub.basics.thread;
import static org.junit.jupiter.api.Assertions.*;
import java.util.concurrent.*;
import org.junit.jupiter.api.*;
import org.junit.jupiter.api.Test;
class CallableExampleTest {
@Test
void testCallable() throws ExecutionException, InterruptedException {
class ExampleCallable implements Callable<Integer> {
@Override
public Integer call() throws Exception {
int sum = 0;
for (int i = 1; i <= 100; ++i) {
sum += i;
}
return sum;
}
}
ExampleCallable exampleCallable = new ExampleCallable();
FutureTask<Integer> futureTask = new FutureTask<>(exampleCallable);
new Thread(futureTask).start();
assertEquals(5050, futureTask.get());
}
@Test
void testThreadPool() throws ExecutionException, InterruptedException {
class ExampleCallable implements Callable<Integer> {
@Override
public Integer call() throws Exception {
int sum = 0;
for (int i = 1; i <= 100; ++i) {
sum += i;
}
return sum;
}
}
ExecutorService executorService = Executors.newFixedThreadPool(1);
Future<Integer> result = executorService.submit(new ExampleCallable());
int callableSum = result.get();
Assertions.assertEquals(5050, callableSum);
executorService.shutdown();
}
}