小明往一张银行卡里面存钱,小美和小娟从这张银行卡中取钱。小美和小娟每次随机取50-100块钱,当里面没钱后,通知小明存钱。小明每次存1000元,存完后通知小美和小娟取钱。
import java.util.Random;
public class Resource {
private int money;
private boolean isEmpty = true;
public void push(int money) {
synchronized ("") {
if (!isEmpty) {
try {
"".wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
this.money += money;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "存了" + money + "元,还剩"+this.money);
isEmpty = false;
"".notify();
}
}
public void pop() {
synchronized ("") {
if (isEmpty) {
try {
"".wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Random r = new Random();
int hua = r.nextInt(50) + 50;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (money < hua) {
isEmpty = true;
"".notify();
} else {
money -= hua;
System.out.println(Thread.currentThread().getName() + "花了" + hua + "元,还剩" + money + "元");
}
}
}
}
public class Consumer implements Runnable{
private Resource res;
public Consumer(Resource res) {
this.res = res;
}
@Override
public void run() {
while(true) {
res.pop();
}
}
}
public class Producer implements Runnable{
private Resource res;
public Producer(Resource res) {
this.res = res;
}
@Override
public void run() {
while(true) {
res.push(1000);
}
}
}
public class Test {
public static void main(String[] args) {
Resource res = new Resource();
new Thread(new Consumer(res),"小美").start();
new Thread(new Consumer(res),"小娟").start();
new Thread(new Producer(res),"小明").start();
}
}