Chinaunix

标题: 多线程模拟对同一个账户,一个来存款一个来取款 [打印本页]

作者: QCHuangChao    时间: 2015-07-13 11:01
标题: 多线程模拟对同一个账户,一个来存款一个来取款
多线程访问共享数据
  1. package thread;

  2. /**
  3. * 多线程模拟一个存 一个取,存完通知另一个来取
  4. */
  5. public class ImitateDepositDrawTheadTest {
  6.      
  7.     public static void main(String[] args) {
  8.          
  9.         final DepositOrWithdrawBusiness business = new DepositOrWithdrawBusiness(1000);
  10.         new Thread(new Runnable(){
  11.             @Override
  12.             public void run() {
  13.                 while(true){
  14.                     business.deposit();
  15.                 }
  16.             }
  17.         }).start();
  18.         new Thread(new Runnable(){
  19.             @Override
  20.             public void run() {
  21.                 while(true){
  22.                     business.withdraw();
  23.                 }
  24.             }
  25.         }).start();
  26.          
  27.          
  28.     }
  29. }
  30. class DepositOrWithdrawBusiness{
  31.     int balance = 1000;
  32.     public DepositOrWithdrawBusiness(int balance){
  33.         this.balance = balance;
  34.     }
  35.     boolean isWithdraw = false;
  36.     public synchronized void deposit(){
  37.         if(isWithdraw){
  38.             try {
  39.                 this.wait();
  40.             } catch (InterruptedException e) {
  41.                 e.printStackTrace();
  42.             }
  43.         }
  44.         balance = balance+300;
  45.         System.out.println(Thread.currentThread().getName()+ " deposit $300,now balance:" + balance);
  46.         isWithdraw=true;
  47.         this.notify();
  48.          
  49.     }
  50.     public synchronized void withdraw(){
  51.         if(!isWithdraw){
  52.             try {
  53.                 this.wait();
  54.             } catch (InterruptedException e) {
  55.                 e.printStackTrace();
  56.             }
  57.         }
  58.         balance = balance-300;
  59.         System.out.println(Thread.currentThread().getName()+ " withdraw $300,now balance:" + balance);
  60.         isWithdraw=false;
  61.         this.notify();
  62.     }
  63. }
复制代码
运行结果:
Thread-0 deposit $300,now balance:1300
Thread-1 withdraw $300,now balance:1000
Thread-0 deposit $300,now balance:1300
Thread-1 withdraw $300,now balance:1000
Thread-0 deposit $300,now balance:1300
Thread-1 withdraw $300,now balance:1000
Thread-0 deposit $300,now balance:1300
Thread-1 withdraw $300,now balance:1000
Thread-0 deposit $300,now balance:1300
Thread-1 withdraw $300,now balance:1000
Thread-0 deposit $300,now balance:1300
Thread-1 withdraw $300,now balance:1000
Thread-0 deposit $300,now balance:1300
Thread-1 withdraw $300,now balance:1000
Thread-0 deposit $300,now balance:1300
Thread-1 withdraw $300,now balance:1000
。。。




欢迎光临 Chinaunix (http://bbs.chinaunix.net/) Powered by Discuz! X3.2