在 Java 中,如何让线程互相通信?


线程间通信涉及到线程之间的互相通信。有三种方法可用于在 Java 中实现线程间通信。

wait()

此方法导致当前线程释放锁。此操作会持续到特定时间过去或者另一个线程针对此对象调用 notify() 或 notifyAll() 方法。

notify()

此方法唤醒当前对象监视器上的多个线程中的一个线程。线程的选择是任意的。

Learn Java in-depth with real-world projects through our Java certification course. Enroll and become a certified expert to boost your career.

notifyAll()

此方法唤醒当前对象监视器上的所有线程。

示例

Open Compiler
class BankClient { int balAmount = 5000; synchronized void withdrawMoney(int amount) { System.out.println("Withdrawing money"); balAmount -= amount; System.out.println("The balance amount is: " + balAmount); } synchronized void depositMoney(int amount) { System.out.println("Depositing money"); balAmount += amount; System.out.println("The balance amount is: " + balAmount); notify(); } } public class ThreadCommunicationTest { public static void main(String args[]) { final BankClient client = new BankClient(); new Thread() { public void run() { client.withdrawMoney(3000); } }.start(); new Thread() { public void run() { client.depositMoney(2000); } }.start(); } }

输出

Withdrawing money
The balance amount is: 2000
Depositing money
The balance amount is: 4000 

更新时间: 2023 年 11 月 29 日

5K+ 次浏览

开启您的 职业生涯

完成课程以获得认证

开始
广告