黑马程序员技术交流社区

标题: 多线程例子 [打印本页]

作者: 825176857    时间: 2015-7-13 17:42
标题: 多线程例子
  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. }
复制代码

作者: huangjiawei    时间: 2015-7-13 19:46
学习了,代码很清楚,一目了然
作者: Love丶cd    时间: 2015-7-13 20:31
不错不错。




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2