目标效果
多个线程按顺序轮流进行打印
1. 基于Object的wait、notify方法
public class WaitNotify {
public static void main(String[] args) {
final int num = 20;
Thread[] threads = new Thread[num];
for (int i = 0; i < num; i++) {
final int I = i;
threads[i] = new Thread(() -> {
while (!Thread.interrupted()) {
Thread curr = threads[I];
Thread next = threads[(I + 1) % num];
synchronized (curr) {
try {
curr.wait();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
synchronized (next) {
System.out.println("thread:" + I);
next.notify();
}
}
}
});
}
for (Thread thread : threads) {
thread.start();
}
synchronized (threads[0]) {
threads[0].notify();
}
}
}
2.基于LockSupport的park、unpark方法
更简单一些,并且LockSupport支持指定唤醒线程。
public class WaitNotify {
public static void main(String[] args) {
final int num = 10;
Thread[] threads = new Thread[num];
for (int i = 0; i < num; i++) {
final int I = i;
threads[i] = new Thread(() -> {
while (!Thread.interrupted()) {
LockSupport.park();
System.out.println("thread:" + I);
LockSupport.unpark(threads[(I + 1) % num]);
}
});
}
for (Thread thread : threads) {
thread.start();
}
LockSupport.unpark(threads[0]);
}
}