package jia;
public class panzi {
private int apple;
private int orange;
public panzi() {
apple=0;
orange=0;
}
public synchronized void save(int apple) {
this.apple+=apple;
System.out.println(Thread.currentThread().getName()+"放了"+apple+"个苹果,家里一共"+this.apple+"苹果");
notify();
}
public synchronized void save1(int orange) {
this.orange+=orange;
System.out.println(Thread.currentThread().getName()+"放了"+orange+"个橘子,家里一共"+this.orange+"橘子");
notify();
}
public synchronized void take(int apple) {
if(this.apple>=apple) {
this.apple-=apple;
System.out.println(Thread.currentThread().getName()+"拿了"+apple+"个苹果,家里一共"+this.apple+"苹果");
}
else {
System.out.println("家里没有这么多苹果了");
}
try {
wait();
}catch (InterruptedException e) {
e.printStackTrace();
}
}
public synchronized void take1(int orange) {
if(this.orange>=orange) {
this.orange-=orange;
System.out.println(Thread.currentThread().getName()+"拿了"+orange+"个橘子,家里一共"+this.orange+"橘子");
}
else {
System.out.println("家里没有这么多橘子了");
}
try {
wait();
}catch (InterruptedException e) {
e.printStackTrace();
}
}
}
package jia;
public class baba implements Runnable {
private panzi pz;
public baba(panzi pz) {
this.pz=pz;
}
public void run() {
for(int i =0;i<3;i++) {
pz.save(5);
pz.take(2);
}
}
}
package jia;
public class mama implements Runnable {
private panzi pz;
public mama(panzi pz) {
this.pz=pz;
}
public void run() {
for(int i =0;i<3;i++) {
pz.save1(5);
pz.take(2);
}
}
}
package jia;
public class erzi implements Runnable {
private panzi pz;
public erzi(panzi pz) {
this.pz=pz;
}
public void run() {
for(int i =0;i<3;i++) {
pz.take(3);
pz.take1(2);
}
}
}
package jia;
public class ceshi {
public static void main(String[] args) {
panzi p=new panzi();
baba b=new baba(p);
mama m=new mama(p);
erzi e=new erzi(p);
Thread t=new Thread(b,"爸爸");
Thread t1=new Thread(m,"妈妈");
Thread t2=new Thread(e,"儿子");
t.start();
t1.start();
t2.start();
}
}
package jia;public class panzi { private int apple; private int orange; public panzi() { apple=0; orange=0; } public synchronized void save(int apple) { this.apple+=apple; System.out.println(Thread.currentThread().getName()+"放了"+apple+"...