线程如何在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 恭喜师兄结婚祝福语简短
15 员工集体辞职祝福语简短
16 高中新生祝福语 简短
17 装修祝福语男生搞笑简短
18 生日开业蛋糕祝福语简短