码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2020-03-25 10:42:44      阅读:78      评论:0      收藏:0      [点我收藏+]

标签:not   with   lse   sync   syn   star   wait   obj   tst   

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中的多线程的实现生产者消费者模式

标签:not   with   lse   sync   syn   star   wait   obj   tst   

原文地址:https://www.cnblogs.com/dirsoen/p/12564257.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!