Java 中线程如何相互通信?
javaobject oriented programmingprogramming更新于 2025/6/28 23:40:17
线程间通信涉及线程之间的通信。Java 中用于实现线程间通信的三种方法
wait()
此方法使当前线程 释放锁。直到经过特定时间或另一个线程调用此对象的 notify() 或 notifyAll() 方法,才会释放锁。
notify()
此方法从当前对象监视器上的多个线程中唤醒单个线程。线程的选择是任意的。
notifyAll()
此方法唤醒当前对象监视器上的所有线程。
示例
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
相关文章
有用资源
java 参考教程 - 该教程包含有关 java 的更多信息:https://www.cainiaomax.com/java/

