java中的多線程的實現生產者消費者模式


丈夫類:往銀行賬戶里存錢,存款[0~10000)的隨機數,2秒存一次

妻子類:從銀行賬戶里取錢,取款[0~10000)的隨機數,2秒取一次,如果余額不足,等到丈夫存了錢,再取

public class TestAccount {

  public static void main(String[] args) {
    Account account = new Account();
    account.setAccount("116854398");
    account.setBalance(10);
    Thread t1 = new Wife(account, TestAccount.class);
    Thread t2 = new Husband(account, TestAccount.class);

    t1.start();
    t2.start();
  }
}

 

import java.util.Random;

public class Wife extends Thread{
  private Account account;
  private Object lock;

  public Wife(Account account, Object lock) {
    this.account = account;
    this.lock = lock;
  }

  public void run() {
    while (true) {
      synchronized (lock) {
        Random random = new Random();
        int withDraw = random.nextInt(10000);
        if (account.getBalance() >= withDraw) {
          account.setBalance(account.getBalance() - withDraw);
          System.out.println("妻子取了:" + withDraw + "元");
          System.out.println(account);
          try {
            sleep(2000);
          } catch (InterruptedException e) {
            e.printStackTrace();
          }
        } else {
          try {
            lock.wait();
          } catch (InterruptedException e) {
            e.printStackTrace();
          }
        }
      }
    }
  }
}

 

import java.util.Random;

public class Husband extends Thread{

  private Account account;
  private Object lock;

  public Husband(Account account, Object lock) {
    this.account = account;
    this.lock = lock;
  }

  public void run() {
    while(true) {
      synchronized (lock) {
        Random random = new Random();
        int exists = random.nextInt(10000);
        account.setBalance(account.getBalance() + exists);
        System.out.println("丈夫存了:" + exists + "元");
        System.out.println(account);
        try {
          sleep(2000);
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
        lock.notify();
        }
     }
  }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM