多執行緒問題搶答模擬
package yn.ngems.cn;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
public class ThreadDemo{
public static void main(String[] args) throws Exception{
MyThread thread = new MyThread();
FutureTask<String> ftA = new FutureTask<String>(thread);
FutureTask<String> ftB = new FutureTask<String>(thread);
FutureTask<String> ftC = new FutureTask<String>(thread);
new Thread(ftA,"執行緒A").start();
new Thread(ftB,"執行緒B").start();
new Thread(ftC,"執行緒C").start();
System.out.println(ftA.get());
System.out.println(ftB.get());
System.out.println(ftC.get());
}
}
class MyThread implements Callable<String>{
private boolean flag = false;
@Override
public String call() throws Exception {
Thread.sleep(1000);
synchronized (this) {
if(this.flag == false) {
this.flag = true;
return Thread.currentThread().getName() + "搶答成功!";
}else {
return Thread.currentThread().getName() + "搶答失敗!";
}
}
}
}
同步鎖機制,搶答開關,同時需要一個返回值