java multithreading six: multithreaded analysis of three cases - the competition answer

Article Source https://www.jianshu.com/p/e73cf865fc2d

Articles corresponding video source: https://developer.aliyun.com/course/1012?spm=5176.10731542.0.0.6ef2d290hxQ4g0

Design a bid Responder program: to design three Responder's (three threads), and then issue commands at the same time answer, answer winners give prompt success, not failure to give prompt answer winner.
  For this multithreaded operation, since the data related to the return of which is preferably implemented using 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() + "抢答失败!";
            }
        }
    }
}
Published 52 original articles · won praise 7 · views 10000 +

Guess you like

Origin blog.csdn.net/YKWNDY/article/details/104955593