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