标签:多线程 thread wait notifyall notify
最近在复习Java基础,看到多线程这块顺便写写多线程的协调控制程序。
需求:假设系统中有两个线程分别代表取款者和存款者,现在系统的要求是存款者和取款者不断的重复存、取款操作,
并且要求每当有存款者将钱存入指定账户中时,取款者就立即取出这笔钱,即不允许存款者连续两次存钱,也不允许
取款者两次取钱。
下面代码实现:
1.首先是账户Account类;
package com.xjtu.cruise.soft.thread; public class Account { /** * @author Cruise * @param args */ private String accountNo; //标识账户是否还有存款的 private boolean flag = false; private double balance; public Account(){} public Account(String accountNo, double balance) { this.accountNo = accountNo; this.balance = balance; } public double getBalance(){ return balance; } public synchronized void draw(double drawAmount) { try { if (!flag) { //如果账户没钱 wait(); //阻塞当前的方法,并释放同步锁(这里就是this,也就是调用此方法的对象) } else { System.out.println("线程:" + Thread.currentThread().getName() + "取款" + drawAmount); balance -= drawAmount; System.out.println("账户余额:" + balance); flag = false; notifyAll(); //唤醒等待此同步锁的所有线程 } } catch (InterruptedException e) { e.printStackTrace(); } } public synchronized void deposit(double depositAmount) { try{ if(flag){ //如果账户有存入的钱 wait(); }else{ System.out.println("线程:"+ Thread.currentThread().getName()+"存款"+depositAmount); balance += depositAmount; System.out.println("账户余额:" + balance); flag = true; notifyAll(); } }catch(InterruptedException e){ e.printStackTrace(); } } }
package com.xjtu.cruise.soft.thread; public class DepositThread extends Thread { private Account account; private double depositAmount; public DepositThread(String name, Account account, double depositAmount) { super(name); this.account = account; this.depositAmount = depositAmount; } public void run(){ for(int i=0; i<100; i++){ // System.out.println("线程:" + Thread.currentThread().getName()+"执行存款操作。"); account.deposit(depositAmount); } } }
package com.xjtu.cruise.soft.thread; public class DrawThread extends Thread { /** * @author Cruise * @param args */ private Account account; private double drawAmount; public DrawThread(String name, Account account, double drawAmount) { super(name); this.account = account; this.drawAmount = drawAmount; } public void run(){ for(int i=0; i<100; i++){ // System.out.println("线程:" + Thread.currentThread().getName()+"执行取钱操作。"); account.draw(drawAmount); } } }
package com.xjtu.cruise.soft.thread; public class TestDraw { /** * @author Cruise * @param args */ public static void main(String[] args) { Account account = new Account("123", 0); new DrawThread("取钱者", account, 800).start(); new DepositThread("存款者甲",account, 800).start(); new DepositThread("存款者乙",account, 800).start(); } }
OK, 一个线程协调控制的Demo完成。
标签:多线程 thread wait notifyall notify
原文地址:http://blog.csdn.net/cruise_h/article/details/39060545