1.产品类
public class Product {
public Product(){
System.out.print("生产了一个产品");
}
}
2.生产者类
public class Producer implements Runnable{
private int COUNT_MAX;
private LinkedList<Product> list;
private Lock lock;
private Condition c;
private Condition p;
public Producer(Consumer consumer,int COUNT_MAX){
this.COUNT_MAX = COUNT_MAX;
this.list = consumer.getList();
this.lock = consumer.getLock();
this.c = consumer.getC();
this.p = consumer.getP();
}
@Override
public void run() {
for(;;){
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
lock.lock();
try{
while(list.size() >= COUNT_MAX){
try {
p.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
list.push(new Product());
System.out.println(",还剩下: "+list.size()+"个");
c.signal();
}finally{
lock.unlock();
}
}
}
}
3.消费者类
public class Consumer implements Runnable {
private LinkedList<Product> list = new LinkedList<Product>();
private Lock lock = new ReentrantLock();
private Condition c = lock.newCondition();
private Condition p = lock.newCondition();
public LinkedList<Product> getList() {
return list;
}
public Lock getLock() {
return lock;
}
public Condition getC() {
return c;
}
public Condition getP() {
return p;
}
@Override
public void run() {
for(;;){
try {
TimeUnit.MILLISECONDS.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
lock.lock();
try{
while(list.size() <= 0){
try {
c.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
list.pop();
System.out.println("消费了一个产品,剩: "+list.size()+"个");
p.signal();
}finally{
lock.unlock();
}
}
}
}
4.测试
@Test
public void Test(){
Consumer consumer = new Consumer();
Producer producer = new Producer(consumer,10);
new Thread(consumer).start();
new Thread(consumer).start();
new Thread(producer).start();
new Thread(producer).start();
new Thread(producer).start();
new Thread(producer).start();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}