Java Synchronized - Inter-Thread Synchronization

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()
    唤醒等待的所有线程

inter-thread communication process

  1. 线程等待获取锁
  2. 线程获取锁
  3. 如果调用了wait方法,则线程进入等待状态。否则线程释放锁并退出
  4. 其它线程调用notify方法或notifyall方法,线程进入notified state(runnable state),并且等待获取锁
  5. 线程重新获取锁,执行完任务后释放锁并且退出。

实例

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();
	}
}

内容整理自

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值