写一个固定容量同步容器,拥有put和get方法,以及getCount方法,能够支持2个生产者线程以及10个消费者线程的阻塞调用。
1、synchronized的wait()和notify()方法
代码如下:
public class Test_Container<T> {
final private LinkedList<T> list = new LinkedList();
//最大值为10
final private int Max = 10;
private int count = 0;
public synchronized void put(T t) {
while (list.size() == Max) {
try {
//满了,阻塞
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
list.add(t);
++count;
System.out.println("生产者中被塞了" + count + "个对象");
//塞好了得通知消费者进行消费
this.notifyAll();
}
public synchronized T get() {
T t = null;
while (list.size() == 0) {
try {
//拿空了,不能再拿了,阻塞
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//取第一个对象
t = list.removeFirst();
count--;
System.out.println("生产者中还有" + count + "个对象");
//取好了得通知生产者继续生产
this.notifyAll();
return t;
}
public static void main(String[] args) {
Test_Container<String> container = new Test_Container();
//10个消费者线程
for (int i = 0; i < 10; i++) {
new Thread(() -> {
for (int j = 0; j < 5; j++) {
//每个线程去消费5次
container.get();
}
}, "T" + i).start();
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//2个生产者线程
for (int i = 0; i < 2; i++) {
new Thread(() -> {
for (int j = 0; j < 25; j++) {
//往里生产25次,因为阻塞所以一会塞一会取
container.put(Thread.currentThread().getName() + " " + j);
}
}, "P" + i).start();
}
}
}
结果如下:
2、使用ReentrantLock
上面的程序有个小瑕疵,notify会叫醒所有生产者和消费者。那怎么才能实现生产者只喊醒消费者呢?
ReentrantLock的condition就能实现,可以分组唤醒需要唤醒的线程。
代码如下:
public class Test_Container<T> {
final private LinkedList<T> list = new LinkedList();
//最大值为10
final private int Max = 10;
private int count = 0;
private Lock lock = new ReentrantLock();
private Condition producer = lock.newCondition();
private Condition consumer = lock.newCondition();
//生产者往里塞
public void put(T t) {
try {
lock.lock();
while (list.size() == Max) {
//满了,生产者阻塞
producer.await();
}
list.add(t);
++count;
System.out.println("生产者中被塞了" + count + "个对象");
//塞好了得通知消费者进行消费
consumer.signalAll();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
//消费者消费
public T get() {
T t = null;
try {
lock.lock();
while (list.size() == 0) {
//拿空了,不能再拿了,阻塞
consumer.await();
}
//取第一个对象
t = list.removeFirst();
count--;
System.out.println("生产者中还有" + count + "个对象");
//取好了得通知生产者继续生产
producer.signalAll();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
return t;
}
public static void main(String[] args) {
Test_Container<String> container = new Test_Container();
//10个消费者线程
for (int i = 0; i < 10; i++) {
new Thread(() -> {
for (int j = 0; j < 5; j++) {
//每个线程去消费5次
container.get();
}
}, "T" + i).start();
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//2个生产者线程
for (int i = 0; i < 2; i++) {
new Thread(() -> {
for (int j = 0; j < 25; j++) {
//往里生产25次,因为阻塞所以一会塞一会取
container.put(Thread.currentThread().getName() + " " + j);
}
}, "P" + i).start();
}
}
}