多线程(家里水果)

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

}

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值