线程同步问题

package com.java.thread.synch;
/**
 * 演示线程等待
 * @author hanenze
 * 银行卡上原本有1001快
 * 同时进行,存钱和取钱,但是,当银行卡中的余额不足400时
 * 那么妹妹要等待哥哥存够钱才能取钱
 */
public class HongLouMeng {
	static Object obj=new Object();
	static int Money=1001;
	public static void main(String[] args) {
		LinMeiMei1 run1=new LinMeiMei1(obj);
		BaoGeGe1 run2=new BaoGeGe1(obj);
		Thread meimei=new Thread(run1);
		Thread gege=new Thread(run2);
		meimei.start();
		gege.start();
	}
}
/**
 * 妹妹花钱
 * @author hanenze
 *每个月花400快,花5个月
 */
class LinMeiMei1 implements Runnable{
	private Object obj;
	public LinMeiMei1(Object obj){
		this.obj=obj;
	}
	@SuppressWarnings("static-access")
	public void run(){
		synchronized (obj) {
			for(int i=1;i<=5;i++){
				try {
					obj.notify();
					while(HongLouMeng.Money<400){
						Thread.currentThread().sleep(1000);
						System.out.println("卡上余额不足,林妹妹等待哥哥存钱");
						obj.wait();
					}
					Thread.currentThread().sleep(1000);
					HongLouMeng.Money-=400;
					System.out.println("妹妹第"+i+"次取了400块钱,卡上还剩下"+HongLouMeng.Money+"元");
				} catch (InterruptedException e) {
					e.printStackTrace();
				}

			}
		}
	}
}

/**
 * 哥哥赚钱
 * @author hanenze
 * 每个月存100快,存十个月
 */
class BaoGeGe1 implements Runnable{
	private Object obj;
	public BaoGeGe1(Object obj){
		this.obj=obj;
	}
	@SuppressWarnings("static-access")
	public void run(){
		synchronized (obj) {
			for(int i=1;i<=10;i++){
				try {
					obj.notify();
					while(HongLouMeng.Money>=400&&i!=11){
						obj.wait();
					}
					Thread.currentThread().sleep(1000);
					HongLouMeng.Money+=100;
					System.out.println("第"+i+"个月哥哥存了100块,卡上还剩下"+HongLouMeng.Money+"元");
				} catch (InterruptedException e) {
					e.printStackTrace();
				}

			}
		}
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值