您的位置:首页 > 其它

多个线程同时访问资源

2014-08-15 15:27 197 查看
多个线程同时访问资源,可能发生不同步,或者程序阻塞的现象(即所有的线程都处于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();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐