多个线程同时访问资源,可能发生不同步,或者程序阻塞的现象(即所有的线程都处于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();
}
}