Java 线程间通信
线程间通信或
合作都是关于允许同步线程进行通信的。
协作(线程间通信)是一种机制,其中一个线程在其关键部分暂停运行,而另一个线程被允许进入(或锁定)同一关键部分以进行通信。通过以下
对象类的方法实现:
wait()
notify()
notifyAll()
1)wait()方法
导致当前线程释放锁,并等待直到另一个线程为该线程调用notify()方法或notifyAll()方法
当前线程必须拥有此对象的监视器,因此只能从同步方法中调用它,否则它将引发异常。
方法 |
说明 |
public final void wait()引发InterruptedException |
等待直到通知对象。 |
public final void wait(long timeout)引发InterruptedException |
等待指定的时间。 |
2)notify()方法
唤醒正在此对象的监视器上等待的单个线程。如果有任何线程在该对象上等待,则选择其中一个唤醒。选择是任意的,并且可以根据实现情况进行选择。语法:
public final void notify()
3)notifyAll()方法
唤醒正在此对象的监视器上等待的所有线程。语法:
public final void notifyAll()
了解线程间通信的过程
上图的点对点解释如下:
进入线程以获取锁。
锁是通过线程获取的。
如果您在对象上调用wait()方法,则线程进入等待状态。否则,它将释放锁并退出。
如果调用notify()或notifyAll()方法,则线程将移至已通知状态(可运行状态)。
现在可以使用线程来获取锁。
任务完成后,线程释放锁并退出对象的监视状态。
为什么在对象类而不是线程类中定义了wait(),notify()和notifyAll()方法?
这是因为它们与锁和对象有关有锁。
等待和睡眠之间的区别?
让我们看看等待和睡眠方法之间的重要区别。
wait() |
sleep() |
wait()方法释放锁 |
sleep()方法不会释放锁。 |
是对象类的方法 |
是Thread类的方法 |
是非静态方法 |
是静态方法 |
是非静态方法 |
是静态方法 |
应通过notify()或notifyAll()方法通知 |
在指定的时间后,睡眠完成。 |
java中线程间通信的示例
让我们看一下线程间通信的简单示例。
class Customer{
int amount=10000;
synchronized void withdraw(int amount){
System.out.println("going to withdraw...");
if(this.amount<amount){
System.out.println("Less balance; waiting for deposit...");
try{
wait();
}
catch(Exception e){
}
}
this.amount-=amount;
System.out.println("withdraw completed...");
}
synchronized void deposit(int amount){
System.out.println("going to deposit...");
this.amount+=amount;
System.out.println("deposit completed... ");
notify();
}
}
class Test{
public static void main(String args[]){
final Customer c=new Customer();
new Thread(){
public void run(){
c.withdraw(15000);
}
}
.start();
new Thread(){
public void run(){
c.deposit(10000);
}
}
.start();
}
}
Output: going to withdraw... Less balance;
waiting for deposit... going to deposit... deposit completed... withdraw completed