线程如何在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
热门推荐
10 祝福语简短古诗词
11 分手新年祝福语大全简短
12 合字的祝福语简短
13 航空公司祝福语简短
14 钱包祝福语简短10字
15 朋友花篮开业祝福语简短
16 班级集体生日祝福语简短
17 中考祝福语简短卡片大全
18 年月日祝福语简短