wait 和 notfiy 实现线程同步

来源:互联网 发布:新兵的爆菊经历知乎 编辑:程序博客网 时间:2024/05/19 18:00
//创建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;}@Overridepublic 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;}@Overridepublic 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