设计一个竞拍抢答程序:要求设计三个抢答者(三个线程),而后同时发出抢答指令,抢答成功者给出成功提示,未抢答成功者给出失败提示。
对于这个多线程操作,由于里面涉及到数据返回问题,最好使用Callable实现。
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
public class ThreadDemo {
public static void main(String[] args) throws Exception {
MyThread mt = new MyThread();
FutureTask<String> taskA = new FutureTask(mt);
FutureTask<String> taskB = new FutureTask(mt);
FutureTask<String> taskC = new FutureTask(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());
}
}
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() + "抢答失败!";
}
}
}
}
网友评论