同步容器的生产者消费者模式升级版
package com.qqjx.thread;
import java.util.LinkedList;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class MyContainer2<T> {
final private LinkedList<T> lists = new LinkedList<>();
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(lists.size() == MAX) {
producer.await();
}
lists.add(t);
++count;
consumer.signalAll();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
public T get() {
T t = null;
try {
lock.lock();
while(lists.size() == 0) {
consumer.await();
}
t = lists.removeFirst();
count --;
producer.signalAll();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
return t;
}
public static void main(String[] args) {
MyContainer2<String> c = new MyContainer2<>();
for(int i=0; i<10; i++) {
new Thread(()->{
for(int j=0; j<5; j++) System.out.println(c.get());
}, "c" + i).start();
}
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
for(int i=0; i<2; i++) {
new Thread(()->{
for(int j=0; j<25; j++) c.put(Thread.currentThread().getName() + " " + j);
}, "p" + i).start();
}
}
}
p0 0
p1 4
p1 3
p1 1
p0 2
p1 2
p1 0
p0 7
p0 6
p0 9
p0 5
p0 3
p0 4
p0 1
p1 8
p0 13
p1 7
p1 6
p1 5
p0 17
p0 16
p0 20
p0 14
p0 15
p0 12
p0 11
p1 9
p0 10
p0 8
p1 13
p1 12
p1 11
p1 10
p0 23
p0 22
p0 21
p0 19
p0 18
p0 24
p1 22
p1 23
p1 21
p1 20
p1 19
p1 18
p1 17
p1 16
p1 15
p1 14
p1 24