更新时间:2023-04-07 来源:快连程序员 浏览量:

Java中可以通过wait(), notify()和notifyAll()方法来实现多线程之间的通讯和协作。
wait()方法用于让一个线程等待,直到另一个线程通知它继续执行。当一个线程调用wait()方法时,它会释放当前的锁,然后进入等待状态。等待状态中的线程可以通过notify()或notifyAll()方法来被唤醒。
notify()方法用于唤醒一个等待状态的线程。如果有多个线程等待,只会唤醒其中的一个。如果要唤醒所有等待状态的线程,可以使用notifyAll()方法。
下面是一个简单的示例代码,演示了如何使用wait()、notify()和notifyAll()方法来实现多个线程之间的通讯和协作。
public class ThreadCommunicationDemo {
private Object lock = new Object();
private boolean flag = false;
public static void main(String[] args) {
ThreadCommunicationDemo demo = new ThreadCommunicationDemo();
new Thread(demo::waitThread).start();
new Thread(demo::notifyThread).start();
new Thread(demo::notifyAllThread).start();
}
private void waitThread() {
synchronized (lock) {
while (!flag) {
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("waitThread is notified.");
}
}
private void notifyThread() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (lock) {
flag = true;
lock.notify();
System.out.println("notifyThread notifies one waiting thread.");
}
}
private void notifyAllThread() {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (lock) {
flag = true;
lock.notifyAll();
System.out.println("notifyAllThread notifies all waiting threads.");
}
}
}在这个示例代码中,创建了一个Object类型的锁对象lock,以及一个boolean类型的flag变量。waitThread()方法会在lock对象上等待,直到flag变量为true时才会继续执行。notifyThread()方法会等待1秒钟后将flag变量设置为true,并调用lock对象的notify()方法来唤醒等待在lock对象上的线程。notifyAllThread()方法会等待2秒钟后将flag变量设置为true,并调用lock对象的notifyAll()方法来唤醒等待在lock对象上的所有线程。
运行这个示例代码后,可以看到如下输出:
notifyThread notifies one waiting thread. waitThread is notified. notifyAllThread notifies all waiting threads. waitThread is notified.
这个输出表明,使用notify()方法可以唤醒等待状态中的一个线程,而使用notifyAll()方法可以唤醒所有等待状态的线程。