Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit f3d5825

Browse files
author
someone-1
committed
callable, future
1 parent cd86341 commit f3d5825

File tree

3 files changed

+83
-0
lines changed

3 files changed

+83
-0
lines changed
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
2+
package callableFuture;
3+
4+
public abstract class Callable<V> extends Thread{
5+
Future future;
6+
private V value;
7+
8+
@Override
9+
public void run(){
10+
try {
11+
value = call();
12+
completed(value);
13+
} catch (Exception e) {
14+
System.out.println("Exception in call method");
15+
e.printStackTrace();
16+
}
17+
}
18+
19+
protected abstract V call();
20+
21+
22+
public Future<V> execute(){
23+
this.start();
24+
this.future = new Future();
25+
return future;
26+
}
27+
28+
private void completed(V value){
29+
future.completed(value);
30+
}
31+
}
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
package callableFuture;
2+
3+
public class Future<V> {
4+
private boolean completed;
5+
private V value;
6+
7+
public synchronized V getValue() throws InterruptedException {
8+
while (!completed){
9+
wait();
10+
}
11+
return value;
12+
}
13+
14+
protected synchronized void completed(V value){
15+
completed = true;
16+
this.value = value;
17+
notifyAll();
18+
}
19+
}
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
package callableFuture;
2+
3+
import org.junit.jupiter.api.Assertions;
4+
import org.junit.jupiter.api.Test;
5+
6+
public class CallableFutureTest {
7+
8+
@Test
9+
public void testGetValue() throws InterruptedException {
10+
int value = 100;
11+
CallableTest callableTest = new CallableTest(value);
12+
Future<Integer> callableInt = callableTest.execute();
13+
14+
Assertions.assertEquals(value, callableInt.getValue());
15+
}
16+
}
17+
18+
class CallableTest extends Callable<Integer> {
19+
private int value;
20+
public CallableTest(int value){
21+
this.value = value;
22+
}
23+
24+
@Override
25+
protected Integer call() {
26+
try {
27+
Thread.sleep(1000);
28+
} catch (InterruptedException e) {
29+
e.printStackTrace();
30+
}
31+
return value;
32+
}
33+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /