2年大厂经验,面试还是太紧张,90%的人不会写

package org.example.threadTest;
import lombok.SneakyThrows;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class ConditionTest {
int sum = 0;
Lock lock = new ReentrantLock();
Condition a;
Condition b;
public ConditionTest() {
a = lock.newCondition();
b = lock.newCondition();
}
public Thread printA() {
Thread thread = new Thread(() -> {
while (sum < 100) {
lock.lock();
try {
a.await();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
while (sum < 100) {
System.out.println("a");
sum++;
break;
}
b.signal();
lock.unlock();
}
});
thread.start();
return thread;
}
public Thread printB() {
Thread thread = new Thread(() -> {
while (sum < 100) {
lock.lock();
try {
b.await();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
while (sum < 100) {
System.out.println("b");
sum++;
break;
}
a.signal();
lock.unlock();
}
});
thread.start();
return thread;
}
public void startPrint(Condition condition) {
lock.lock();
condition.signal();
lock.unlock();
}
@SneakyThrows
public static void main(String[] args) {
ConditionTest conditionTest = new ConditionTest();
Thread threadA = conditionTest.printA();
Thread threadB = conditionTest.printB();
while (true) {
if (threadA.getState().equals(Thread.State.WAITING) && threadB.getState().equals(Thread.State.WAITING)) {
System.out.println(threadB.getState());
System.out.println(threadA.getState());
conditionTest.startPrint(conditionTest.a);
break;
}
}
}
}