public class Storage {
private final int MAX_SIZE = 10;
private LinkedList<Integer> list = new LinkedList<>();
private final Lock lock = new ReentrantLock();
private final Condition full = lock.newCondition();
private final Condition empty = lock.newCondition();
private static int count = 1;
public void produce(){
try {
lock.lock();
while (list.size() + 1 > MAX_SIZE){
System.out.println("生产者[" + Thread.currentThread().getName() + "]仓库已满");
full.await();
}
list.add(count);
System.out.println("生产者[" + Thread.currentThread().getName() + "]生产了一个产品" + count++ + " , 库存量为" + list.size());
empty.signal();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
public void consume() {
try {
lock.lock();
while (list.size() == 0){
System.out.println("消费者[" + Thread.currentThread().getName() + "]仓库为空");
empty.await();
}
int x = list.removeFirst();
System.out.println("消费者[" + Thread.currentThread().getName() + "]消费一个产品" + x +" , 库存量 " + list.size());
full.signal();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
}
public class Consumer implements Runnable{
private Storage storage;
public Consumer() {
}
public Consumer(Storage storage) {
this.storage = storage;
}
@Override
public void run() {
while(true){
try{
Thread.sleep(3000);
storage.consume();
}catch (InterruptedException e){
e.printStackTrace();
}
}
}
}
public class Producer implements Runnable{
private Storage storage;
public Producer() {
}
public Producer(Storage storage) {
this.storage = storage;
}
@Override
public void run() {
while (true) {
try {
Thread.sleep(1000);
storage.produce();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class Main {
public static void main(String[] args) {
Storage storage = new Storage();
Thread p1 = new Thread(new Producer(storage),"生产者线程1");
Thread p2 = new Thread(new Producer(storage),"生产者线程2");
Thread p3 = new Thread(new Producer(storage),"生产者线程3");
Thread c1 = new Thread(new Consumer(storage),"消费者线程1");
Thread c2 = new Thread(new Consumer(storage),"消费者线程2");
Thread c3 = new Thread(new Consumer(storage),"消费者线程3");
p1.start();
p2.start();
p3.start();
c1.start();
c2.start();
c3.start();
}
}
。。。。