package com.sukai.concurrency.test;
import java.util.Queue;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
public class factory<E> {
private Queue<E> queue;
private int maxSize;
private ReentrantLock lock = new ReentrantLock();
private Condition notfull = lock.newCondition();
private Condition notemtry = lock.newCondition();
// 构造函数
public factory(Queue<E> queue, int maxSize) {
this.queue = queue;
this.maxSize = maxSize;
}
// 生产
public void put(E e) throws InterruptedException {
lock.lock();
try {
while (queue.size() == maxSize) {
notemtry.await();
}
queue.add(e);
System.out.println("新增一个元素");
notfull.signal();
} finally {
lock.unlock();
}
}
// 消费
public void take() throws InterruptedException {
lock.lock();
try {
while (queue.size() == 0) {
notfull.await();
}
queue.remove();
System.out.println("删除一个元素");
notemtry.signal();
} finally {
lock.unlock();
}
}
}
package com.sukai.concurrency.test;
import java.util.LinkedList;
import java.util.Queue;
public class Main {
public static void main(String[] args) {
Queue<Integer> queue = new LinkedList<>();
factory<Integer> factory = new factory<>(queue, 5);
consumer<Integer> consumer = new consumer<>(factory, 233);
productor<Integer> productor = new productor<>(factory);
new Thread(consumer).start();
new Thread(productor).start();
}
}
class consumer<E> implements Runnable {
private factory<E> factory;
private E e;
public consumer(factory<E> factory, E e) {
this.factory = factory;
this.e = e;
}
@Override
public void run() {
try {
for (int i = 0; i < 10; i++) {
factory.put(e);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
class productor<E> implements Runnable {
private factory<E> factory;
public productor(factory<E> factory) {
this.factory = factory;
}
@Override
public void run() {
for (int i = 0; i < 10; i++) {
try {
factory.take();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
通过生产者消费者模式的编写,可以了解线程间的通信问题,通过condition的signal和await进行唤醒和等待比wait和notify更好,因为signal和await可以针对特定的线程进行唤醒和等待,比notifyAll更安全。