-
Notifications
You must be signed in to change notification settings - Fork 0
/
CallableDemo.java
36 lines (30 loc) · 1021 Bytes
/
CallableDemo.java
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
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
public class CallableDemo {
public static void main(String[] args) {
MyThread myThread = new MyThread();
FutureTask<String> taskA = new FutureTask<String>(myThread);
FutureTask<String> taskB = new FutureTask<String>(myThread);
FutureTask<String> taskC = new FutureTask<String>(myThread);
Thread threadA = new Thread(taskA, "线程A");
Thread threadB = new Thread(taskB, "线程B");
Thread threadC = new Thread(taskC, "线程C");
threadA.start();
threadB.start();
threadC.start();
}
}
class MyThread implements Callable<String> {
private boolean flag = false;
public String call() throws Exception {
synchronized (this) {
if (this.flag == false) {
System.out.println(Thread.currentThread().getName() + " - 抢答成功!");
this.flag = true;
} else {
System.out.println(Thread.currentThread().getName() + " - 抢答失败!");
}
}
return null;
}
}