当前位置: 移动技术网 > IT编程>开发语言>Java > java中的多线程的实现生产者消费者模式

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

2020年03月25日  | 移动技术网IT编程  | 我要评论
丈夫类:往银行账户里存钱,存款[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();
        }
     }
  }
}

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网