实现一个抢答的程序:要求设置三个抢答者(线程),之后同时发出抢答指令,抢答成功提示,未抢答成功返回失败。
牵扯到数据返回,使用Callable是比较方便的处理方式。
package wzr.thread.test3;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
public class RushToAnswerTest {
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,"answer-A").start();
new Thread(taskB,"answer-B").start();
new Thread(taskC,"answer-C").start();
System.out.println(taskA.get());
System.out.println(taskB.get());
System.out.println(taskC.get());
}
}
class MyThread implements Callable<String>{
private boolean flag=true;
@Override
public String call() throws Exception {
synchronized(this) {
if(this.flag==true) {
this.flag=false;
return Thread.currentThread().getName()+"抢答成功!";
}else {
return Thread.currentThread().getName()+"抢答失败!";
}
}
}
}