线程如何在Java中相互通信?
线程间通信使线程之间的通信不断发展。用于在Java中实现线程间通信的三种方法
等待()
此方法使当前线程 释放锁。直到完成特定时间段或另一个线程为此对象调用notify()或notifyAll() 方法,该操作才完成。
通知()
此方法从当前对象的监视器上的多个线程中唤醒一个线程。线程的选择是任意的。
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