600字范文,内容丰富有趣,生活中的好帮手!
600字范文 > java 多线程 消费者_java中的多线程的实现生产者消费者模式

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

时间:2023-02-04 14:09:49

相关推荐

java 多线程 消费者_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();

}

}

}

}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。