欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

java中的多线程的实现生产者消费者模式

程序员文章站 2022-05-29 13:05:44
丈夫类:往银行账户里存钱,存款[0~10000)的随机数,2秒存一次 妻子类:从银行账户里取钱,取款[0~10000)的随机数,2秒取一次,如果余额不足,等到丈夫存了钱,再取 public class TestAccount { public static void main(String[] ar ......

丈夫类:往银行账户里存钱,存款[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();
        }
     }
  }
}