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

Posted dirsoen

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java中的多线程的实现生产者消费者模式相关的知识,希望对你有一定的参考价值。

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();
        }
     }
  }
}

以上是关于java中的多线程的实现生产者消费者模式的主要内容,如果未能解决你的问题,请参考以下文章

Java多线程:生产者消费者模型

我的多线程—多线程与设计模式阅读笔记

基于Thread+queue的多线程爬虫

java-Runnable加锁实现生产者和消费者的多线程问题

生产者消费者简单实现(转载)

Java 中的多线程你只要看这一篇就够了