在控制台循环打印A和B
使用notify和wait来实现交替打印
public class PrintAAndB {
public static void main(String[] args) {
new ThreadA().start();
new ThreadB().start();
}
private static final Object lock = new Object();
static class ThreadA extends Thread {
@Override
public void run() {
while (true) {
synchronized (lock) {
lock.notify();
System.out.println(Thread.currentThread().getName() + " " + "A");
try {
sleep(1000); // 1s打印一次
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
static class ThreadB extends Thread {
@Override
public void run() {
while (true) {
synchronized (lock) {
lock.notify();
System.out.println(Thread.currentThread().getName() + " " + "B");
try {
sleep(1000); // 1s打印一次
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
打印结果:
Thread-0 A
Thread-1 B
Thread-0 A
Thread-1 B
Thread-0 A
…
使用阻塞队列来实现
使用CyclicBarrier实现
使用自旋实现
使用ReentrantLock实现
使用信号量实现
正在路上…