思路:
在程序的设计过程中涉及到了数据的返回,所以选择callable接口来实现较为方便。
代码实现:
package Demo_2_3_多线程的竞猜抢答; import java.util.concurrent.Callable; public 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() + "抢答失败!"; } } } }
package Demo_2_3_多线程的竞猜抢答; import java.util.concurrent.ExecutionException; import java.util.concurrent.FutureTask; public class Main { public static void main(String[] args) throws Exception{ MyThread mt = new MyThread(); FutureTask<String> task1 = new FutureTask<>(mt); FutureTask<String> task2 = new FutureTask<>(mt); FutureTask<String> task3 = new FutureTask<>(mt); new Thread(task1,"竞赛者A").start(); new Thread(task2,"竞赛者B").start(); new Thread(task3,"竞赛者C").start(); System.out.println(task1.get()); System.out.println(task2.get()); System.out.println(task3.get()); } }
输出结果
(详见Callable)