package com.springboot.leetcode;
/**
* @author Created by leo_args.
* @date 2020/12/8
*
* 主要思路是使用成员变量,作为多线程间的排序因子
* 排序因子可选项比较多 int Atomic…… Queue CountDownLatch Stack Semaphore 等
*/
class Foo {
private volatile int flag = 1;
public Foo() {
}
public void first(Runnable printFirst) throws InterruptedException {
// printFirst.run() outputs "first". Do not change or remove this line.
printFirst.run();
synchronized (this){
flag++;
}
}
public void second(Runnable printSecond) throws InterruptedException {
// printSecond.run() outputs "second". Do not change or remove this line.
for (;;){
if(flag == 2){
break;
}
}
printSecond.run();
synchronized (this){
flag++;
}
}
public void third(Runnable printThird) throws InterruptedException {
// printThird.run() outputs "third". Do not change or remove this line.
for (;;){
if(flag == 3){
break;
}
}
printThird.run();
synchronized (this){
flag++;
}
}
public static void main(String[] args) {
Foo foo = new Foo();
Thread threadA = new Thread(new Runnable() {
@Override
public void run() {
try {
foo.second(new Runnable() {
@Override
public void run() {
System.out.print("second");
}
});
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
Thread threadB = new Thread(new Runnable() {
@Override
public void run() {
try {
foo.first(new Runnable() {
@Override
public void run() {
System.out.print("first");
}
});
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
Thread threadC = new Thread(new Runnable() {
@Override
public void run() {
try {
foo.third(new Runnable() {
@Override
public void run() {
System.out.print("third");
}
});
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
threadA.start();
threadB.start();
threadC.start();
}
}