题目:抢答器,三人抢答,只有一人抢答成功,其余的失败。
class MyThread implements Callable<String>{
private boolean flag = false;
@Override
public String call() throws Exception {
synchronized (this) {
if(this.flag == false) {
this.flag = true ;
return Thread.currentThread().getName()+"抢答成功";
}else {
return Thread.currentThread().getName()+"抢答失败";
}
}
}
}
public class test3 {
public static void main(String[] args) throws Exception {
MyThread mt = new MyThread();
FutureTask<String> taskA = new FutureTask<String>(mt);
FutureTask<String> taskB = new FutureTask<String>(mt);
FutureTask<String> taskC = new FutureTask<String>(mt);
new Thread(taskA,"竞赛者A").start();
new Thread(taskB,"竞赛者B").start();
new Thread(taskC,"竞赛者C").start();
System.out.println(taskA.get());
System.out.println(taskB.get());
System.out.println(taskC.get());
}
}