生产消费者同步容器
利用wait(),notifyAll(),方法交替生产和消费容器内变量,利用同步锁实现同步容器
/**
* @ClassName:MyContainer
* @Description:TODO使用wait(),notifyAll(),编写生产者消费者容器,get,put方法,2个生产线程
* 10个消费线程
* @Author:ZY
* @Date:2019/6/24 0024 23:23
* @Version:1.0
**/
public class MyContainer<T> {
//非静态容器
final LinkedList<T> containList = new LinkedList<T>();
private Integer count = 0;
private static final Integer MAX = 100;
public synchronized void put(T t) {
while (containList.size() == MAX) {
try {
this.wait();
} catch (Exception e) {
e.printStackTrace();
}
}
containList.add(t);
++count;
this.notifyAll();
}
public synchronized T get() {
while (containList.size() == 0) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
T t = containList.removeFirst();
count--;
this.notifyAll();
return t;
}
public static void main(String[] args) {
final MyContainer<String> container = new MyContainer<String>();
for (int i = 0; i < 2; i++) {
new Thread(new Runnable() {
public void run() {
for (int i1 = 0; i1 < 500; i1++) {
container.put(Thread.currentThread().getName() + i1);
}
}
},"product" + i).start();
}
try {
Thread.sleep(2000);
} catch (Exception e) {
e.printStackTrace();
}
for (int i = 0; i < 10; i++) {
new Thread(new Runnable() {
public void run() {
for (int i1 = 0; i1 < 100; i1++) {
System.out.println(container.get());
}
}
},"consumer" + i).start();
}
}
}