Inter-thread communication是指允许同步的线程之间交互,它通过Object class的以下三个方法实现
- wait()
当前线程释放锁 等待另一个线程调用notify或notifyall方法或者等待一定长度的时间
当前对象必须持有锁,才能调用wait方法,
Method Description
public final void wait()throws InterruptedException waits until object is notified.
public final void wait(long timeout)throws InterruptedException waits for the specified amount of time.
- notify()
Wakes up a single thread that is waiting on this object’s monitor. If any threads are waiting on this object, one of them is chosen to be awakened. The choice is arbitrary and occurs at the discretion of the implementation
唤醒等待在此对象上的单个线程 如果有多个对象在等待,则选择其中一个唤醒。这个选择是任意的
- notifyAll()
唤醒等待的所有线程
- 线程等待获取锁
- 线程获取锁
- 如果调用了wait方法,则线程进入等待状态。否则线程释放锁并退出
- 其它线程调用notify方法或notifyall方法,线程进入notified state(runnable state),并且等待获取锁
- 线程重新获取锁,执行完任务后释放锁并且退出。
实例
package com.zhang.learn.effective_java;
class Customer{
int amount = 0;
synchronized void withdraw(int amount) {
System.out.println("goint to withdraw");
if(this.amount < amount) {
System.out.println("refused to withdraw");
try {
wait();
}catch(Exception e) {
e.printStackTrace();
}
}
this.amount -= amount;
System.out.println("end withdraw");
System.out.println(this.amount);
}
synchronized void deposit(int amount) {
System.out.println("goint to deposit");
this.amount += amount;
System.out.println("quit deposit");
notify();
}
}
public class inter_thread_communication_test {
public static void main(String[] args) {
final Customer c = new Customer();
new Thread() {
public void run() {
c.withdraw(3);
}
}.start();
new Thread() {
public void run() {
c.deposit(2);
}
}.start();
}
}