wait 和 notfiy 实现线程同步

//创建Account账户,存取款方法

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Account {
	private double balance;//余额,共享资源
	//private Lock lock = new ReentrantLock();
	//private Condition cond = lock.newCondition();
	//存款方法
	public void deposit(double amount) throws InterruptedException{
		//创建锁
		synchronized(this){
			System.out.println("开始存款" + balance);
			balance += amount;
			notify();
			//延时
			//Thread.sleep((int)(Math.random() * 100 + 200));
			System.out.println("存款结束" + balance);
		}
		
	}
	//取款
	public void withdraw(double amount) throws InterruptedException {
		synchronized (this) {
			//循环判断条件
			while (balance < amount){
				System.out.println("准备取款,判断余额:" + balance + "取款金额为:" + amount);
				wait();
			}
			System.out.println("开始取款" + balance);
			balance -= amount;	
			System.out.println("取款结束" + balance);
		}
	}
	public double getBalance(){
		return balance;
	}
	
}
//存款线程

public class DepositTask implements Runnable {
	private Account account;
	
	public  DepositTask(Account account) {
		this.account  = account;
	}
	@Override
	public void run() {
		try {
			while(true){
			account.deposit((Math.random() * 1000));
			}
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

}
//取款线程

public class WithdrawTask implements Runnable {
	private Account account;
	
	public WithdrawTask(Account account) {
			this.account = account;
	}
	@Override
	public void run() {
		try {
			while(true){
			account.withdraw(Math.random() * 500);
			}
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

}

//测试


import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


public class Test {


public static void main(String[] args) {
Account account = new Account();

ExecutorService pool = Executors.newFixedThreadPool(2);
//存款任务
pool.execute(new DepositTask(account));
//取款任务
pool.execute(new WithdrawTask(account));

pool.shutdown();
//等待全部线程结束
while(!pool.isTerminated());
System.out.println(account.getBalance());
}


}




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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值