多线程同步互斥

 import java.util.Random; 



/**
 * 存钱与取钱的互斥
 * @author Tang
 * @Date 2014年9月26日 16:44:22
 *
 */
public class MultiThreadDemo {


public static final int targetMoney = 10000;//目标存钱值
public static int initMoney = 0;//初始钱


public static void main(String[] args) {
Object object = new Object();
CunQianThread cunQianThread = new CunQianThread(object);
QuQianThread quQianThread = new QuQianThread(object);
Thread thread1 = new Thread(cunQianThread);
Thread thread2 = new Thread(quQianThread);
thread1.start();
thread2.start();
}


//存钱线程
private static class CunQianThread implements Runnable{


private Object object;

public CunQianThread(Object object) {
super();
this.object = object;
}


@Override
public void run() {
Random random = new Random();
while (true) {
int sjMoney = random.nextInt(5001);
cunQianFun(sjMoney);
}


}


private void cunQianFun(int pushMoney) {


synchronized (object) {
try {
// 如果存的钱大于等于目标的钱,开启线程等待
while (MultiThreadDemo.initMoney >= MultiThreadDemo.targetMoney) {
System.out.println("存入的钱已大于" + MultiThreadDemo.targetMoney + ",可以使用了。");
object.wait();//等待
}
Thread.sleep(100);//休眠
MultiThreadDemo.initMoney += pushMoney;
System.out.println("存入 " + pushMoney + "元,剩余总金额 " + MultiThreadDemo.initMoney
+ "。");
object.notifyAll();//重新启动线程
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}

//取钱线程
private static class QuQianThread implements Runnable {

private Object object;

public QuQianThread(Object object) {
super();
this.object = object;
}


@Override
public void run() {
Random random = new Random();
while (true) {
int sjMoney = random.nextInt(15001);
quQianFun(sjMoney);
}
}


private void quQianFun(int pupMoney) {
synchronized (object) {

try {
// 如果存的钱大于等于目标的钱,开启线程等待
while (MultiThreadDemo.initMoney <= 0) {
System.out.println("只剩下" + MultiThreadDemo.initMoney
+ ",要开始存钱了。");
object.wait();//等待
}
Thread.sleep(100);//休眠
MultiThreadDemo.initMoney -= pupMoney;
System.out.println("取出 " + pupMoney + "元,剩余总金额"
+ MultiThreadDemo.initMoney + "。");
object.notifyAll();//重新启动线程
} catch (InterruptedException e) {
e.printStackTrace();
}
}


}
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值