java竞争抢答器

/*实现一个竞拍抢答程序:要求设置三个抢答者(三个线程),而后同时发出抢答指令,抢答成功者显示成功提示,抢答失败者给出失败提示。*/
package Java多线程_01;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
class MyThread_08 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 homework_03 {
	public static void main(String[] args) throws Exception{
		MyThread_08 mt = new MyThread_08();
		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());
	}
}

  

  

点赞