package com.indi.wzl.Lock;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* 生产者-消费者模型, lock.condition awiat()/single
* @Auther: zonglin_wu
* @Date: 2020/2/5 16:54
* @Description:
*/
public class ProducerConsumer2 {
public class Mystack {
public List<String> list = new ArrayList<>();
//生产者消费者共同的锁
public Lock lock = new ReentrantLock();
//生产者条件
public Condition pCondition = lock.newCondition();
//消费者条件
public Condition cCondition = lock.newCondition();
public void push() {
try{
lock.lock();
String name = Thread.currentThread().getName();
if (list.size() == 10) {
pCondition.await();
System.out.println(name+":notify");
}
list.add("1");
System.out.println(name+": push=" + list.size());
//唤醒所有的消费者
cCondition.signalAll();
//生产完一个就休息
pCondition.await();
}catch (Exception e){
e.printStackTrace();
}finally {
lock.unlock();
}
}
public String pop(){
try{
lock.lock();
String name = Thread.currentThread().getName();
while (list.size() == 0) {
System.out.println(name + ":wait");
cCondition.await();
System.out.println(name+":notify");
}
String value = list.get(0);
System.out.println(name + ":getValue:" + value + ",size:" + list.size());
list.remove(0);
pCondition.signalAll();
return value;
}catch (Exception e){
e.printStackTrace();
}finally {
lock.unlock();
}
return null;
}
}
public class ProducerTest extends Thread {
public Mystack mystack;
public ProducerTest(Mystack mystack) {
this.mystack = mystack;
}
@Override
public void run() {
int i = 0;
while (true){
/*try {
Thread.currentThread().sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}*/
mystack.push();
i++;
if (i == 100){
break;
}
}
}
}
public class ConsumerTest extends Thread {
public Mystack mystack;
public ConsumerTest(Mystack mystack) {
this.mystack = mystack;
}
@Override
public void run() {
while (true){
mystack.pop();
}
}
}
public static void main(String[] args) {
ProducerConsumer2 test = new ProducerConsumer2();
Mystack mystack = test.new Mystack();
ProducerTest producerTest1 = test.new ProducerTest(mystack);
ProducerTest producerTest2 = test.new ProducerTest(mystack);
ConsumerTest consumerTest1 = test.new ConsumerTest(mystack);
ConsumerTest consumerTest2 = test.new ConsumerTest(mystack);
ConsumerTest consumerTest3 = test.new ConsumerTest(mystack);
ConsumerTest consumerTest4 = test.new ConsumerTest(mystack);
producerTest1.setName("p1");
producerTest2.setName("p2");
consumerTest1.setName("c1");
consumerTest2.setName("c2");
consumerTest3.setName("c3");
consumerTest4.setName("c4");
producerTest1.start();
producerTest2.start();
consumerTest1.start();
consumerTest2.start();
consumerTest3.start();
consumerTest4.start();
}
}
生产者消费者2-lock.condition awiat()/single
最新推荐文章于 2022-05-31 11:25:08 发布