import java.util.LinkedList;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
public class StudyJava {
Buffer mBuffer = new Buffer(5);;
/**
* @param args
*/
public static void main(String[] args) {
StudyJava s = new StudyJava();
Productor p = s.new Productor();
Consumer c = s.new Consumer();
Thread tp = new Thread(p);
Thread tc = new Thread(c);
tc.start();
tp.start();
}
class Productor implements Runnable{
public void run() {
while(true){
int i = (int)(Math.random()*1000);
mBuffer.add(i);
System.out.println("add " + i);
}
}
}
class Consumer implements Runnable{
public void run() {
while(true){
int i = mBuffer.get();
System.out.println("del " + i);
}
}
}
}
class Buffer {
LinkedList<Integer> buffer;
int mSize;
int currentSize = 0;
ReentrantLock lock = new ReentrantLock();
Condition c = lock.newCondition();//这儿只new了一个condition,因为add/get要在同一个condition上await/signal
public Buffer(int size) {
buffer = new LinkedList<Integer>();
mSize = size;
}
synchronized void addElement(int i) {
if (currentSize >= mSize) {
try {
System.out.println("full");
wait();
} catch(Exception e) {
}
}
currentSize++;
buffer.add(i);
notifyAll();
}
synchronized int getElement() {
if (currentSize <= 0) {
try {
System.out.println("empty");
wait();
} catch(Exception e) {
}
}
currentSize--;
int i = buffer.remove();
notifyAll();
return i;
}
void add(int i) {
lock.lock();
if (currentSize >= mSize) {
try {
System.out.println("full");
c.await();//和condition,lock对应的不能使用wait方法,只能使用await/signal,wait/notify只能用于同步方法
} catch(Exception e) {
}
}
currentSize++;
buffer.add(i);
c.signalAll();
lock.unlock();
}
int get() {
lock.lock();
if (currentSize <= 0) {
try {
System.out.println("empty");
c.await();
} catch(Exception e) {
}
}
currentSize--;
int i = buffer.remove();
c.signalAll();
lock.unlock();
return i;
}
}