测试没毛病,其实就是 `synchronized ,wait , notify`几个函数
@
yazinnnn 这题一毛钱意义都没有,实际业务中没写过这样的逻辑,主要是考察对多线程的熟悉程度吧.
public class TestMain {
private static class MyThread extends Thread{
private final int flag;
private final String str;
private final Object lock;
private final AtomicInteger counter;
public MyThread(int flag, String str,Object lock,AtomicInteger counter) {
this.flag = flag;
this.str = str;
this.lock = lock;
this.counter = counter;
}
@
Override public void run() {
synchronized (lock) {
while (counter.get() < 300) {
if (counter.get() % 3 == flag) {
System.out.print(str);
if (Objects.equals(str,"c")){
System.out.println();
}
counter.incrementAndGet();
lock.notifyAll();
} else {
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
public static void main(String[] args) {
AtomicInteger counter = new AtomicInteger(0);
Object lock = new Object();
MyThread threadA = new MyThread(0,"a",lock,counter);
MyThread threadB = new MyThread(1,"b",lock,counter);
MyThread threadC = new MyThread(2,"c",lock,counter);
threadA.start();
threadB.start();
threadC.start();
try {
threadA.join();
threadB.join();
threadC.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}