多个线程同时访问资源

多个线程同时访问资源,可能发生不同步,或者程序阻塞的现象(即所有的线程都处于wait状态),比如,两个生产者同时生产,两个消费者同时消费:


package test;



class Resources {
	private static Resources mRes = null;
	private String mName;
	private boolean mFlag = false;
	private int mNumber = 1;

	private Resources() {
	}

	public static Resources getInstance() {
		if (mRes == null) {
			synchronized (Resources.class) {
				if (mRes == null) {
					mRes = new Resources();
				}
			}
		}

		return mRes;
	}

	public synchronized void set(String name) {
		//如果已经生成了一个商品,就等待消费者消费
		while (mFlag) {
			try {
				wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		mName = name + "--" + mNumber++;
		System.out.println(Thread.currentThread().getName() + "---------生成者: " + mName );
		try {
			Thread.sleep(50);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		mFlag = true;
		notifyAll();
	}

	public synchronized void out() {
		//如果消费了商品后,就等待生产者生成
		while (!mFlag) {
			try {
				wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		System.out.println(Thread.currentThread().getName() + "消费者: " + mName);
		try {
			Thread.sleep(50);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		mFlag = false;
		notifyAll();

	}
}

class Product implements Runnable{
	public void run(){
		Resources res = Resources.getInstance();
		while (true)
			res.set("--------------商品----");
	}
}

class Consumer implements Runnable{
	public void run(){
		Resources res = Resources.getInstance();
		while (true)
			res.out();
	}
}

测试代码:

public class Main {

	public static void main(String[] args) {
		Product p = new Product();
		Consumer c = new Consumer();
		
		new Thread(p).start();
		new Thread(p).start();
		new Thread(c).start();
		new Thread(c).start();
	}
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值