在 Java 中,如何让线程互相通信?
线程间通信涉及到线程之间的互相通信。有三种方法可用于在 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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP