多线程同步互斥

来源:互联网 发布:proteus单片机教程 编辑:程序博客网 时间:2024/05/21 06:46
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
原创粉丝点击