今天参加面试,面试官出了到如题的面试题,突然就想起了wait/notify,但是好久没写了,忘记了,就记录下,加深下印象
public class TestDemo {
private static final AtomicInteger min = new AtomicInteger(1);
private static final int max = 20;
public static void main(String[] args) {
Object lock = new Object();
new Thread(() -> {
synchronized (lock) {
while (true) {
try {
if (min.get() % 2 == 0) {
lock.wait();
}
System.out.println("thread 1 " + min.get());
Thread.sleep(1000);
lock.notifyAll();
int value = min.incrementAndGet();
if (value >= max) {
break;
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}).start();
new Thread(() -> {
synchronized (lock) {
while (true) {
try {
if (min.get() % 2 == 1) {
lock.wait();
}
Thread.sleep(1000);
System.out.println("thread 2 " + min.get());
lock.notifyAll();
int value = min.incrementAndGet();
if (value >= max) {
break;
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
}
}