public class Storage {
private LinkedList<String> mStringLinkedList = new LinkedList<>();
private int MAX = 10;
private static final String TAG = "zhoumao";
public void consume() {
synchronized (mStringLinkedList) {
while (mStringLinkedList.size() == 0) {
try {
Log.d(TAG, "consume: " + mStringLinkedList.size());
mStringLinkedList.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Log.d(TAG, "consume: " + mStringLinkedList.remove());
mStringLinkedList.remove();
mStringLinkedList.notifyAll();
}
}
public void product() {
synchronized (mStringLinkedList) {
while (mStringLinkedList.size() == MAX) {
try {
Log.d(TAG, "product: " + mStringLinkedList.size());
mStringLinkedList.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Log.d(TAG, "product: " + mStringLinkedList.add("abc"));
mStringLinkedList.add("abc");
mStringLinkedList.notifyAll();
}
}
}
public class Consumer extends Thread {
Storage mStorage;
public Consumer(Storage storage) {
this.mStorage = storage;
}
@Override
public void run() {
mStorage.consume();
}
}
public class Productor extends Thread {
Storage mStorage;
public Productor(Storage storage) {
this.mStorage = storage;
}
@Override
public void run() {
mStorage.product();
}
}
测试代码
Storage storage=new Storage();
new Consumer(storage).start();
new Productor(storage).start();
for (int i =0;i<10;i++){
new Productor(storage).start();
}
new Consumer(storage).start();
new Productor(storage).start();
new Consumer(storage).start();
new Productor(storage).start();