java多线程wait/notify练习案例:线程通信
制作两个线程对象,要求用同步块的方式使第一个线程运行2次,然后将自己阻塞起来,唤醒第二个线程,第二个线程再运行2次,然后将自己阻塞起来,唤醒第一个线程……两个线程交替执行。
public class Demo {
public static void main(String[] args) {
byte[] bytes = new byte[0];
new Thread(() -> {
int count = 0;
synchronized (bytes) {
while (true) {
System.out.println(Thread.currentThread().getName() + "执行了...");
++count;
if (count > 2) {
try {
bytes.notifyAll();
count = 1;
bytes.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}, "线程1").start();
new Thread(() -> {
int count = 0;
synchronized (bytes) {
while (true) {
System.out.println(Thread.currentThread().getName() + "执行了...");
++count;
if (count > 2) {
try {
bytes.notifyAll();
count = 1;
bytes.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}, "线程2").start();
}
}
运行结果:
分析:主要用到wait/notify两个方法
实现 wait/notify 机制的条件:
调用 wait 线程和 notify 线程必须拥有相同对象锁。
- wait 方法和 notify/notifyAll 方法必须在 Synchronized 方法或代码块中。
- 由于 wait/notify 方法是定义在 java.lang.Object中,所以在任何 Java 对象上都可以使用。
案例中,使用同一锁对象唤醒其他等待中的线程