package com.wan.situ;
import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class ThreadLockTest {
public final int MAX_SIZE = 10;
public final Queue<String> mQueue = new LinkedList<>();
public boolean mRunState = false;
public Producer worker;
public Consumer consumer;
private static int index;
private final Lock lock = new ReentrantLock();
private final Condition consumerCondition = lock.newCondition();
private final Condition producerCondition = lock.newCondition();
public synchronized String getNewIndex() {
return (index++) + "";
}
public ThreadLockTest() {
this.worker = new Producer();
this.consumer = new Consumer();
}
public void start() {
this.mRunState = true;
this.consumer.start();
this.worker.start();
}
class Producer extends Thread {
@Override
public void run() {
while (mRunState) {
lock.lock();
while (mQueue.size() == MAX_SIZE) {
try {
System.out.println("生产者 + wait");
producerCondition.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
try {
Thread.sleep(1000);
String p = getNewIndex();
if (mQueue.offer(p)) {
System.out.println("生产者 + " + p);
}
consumerCondition.signal();
} catch (InterruptedException e) {
e.printStackTrace();
}
lock.unlock();
}
}
}
class Consumer extends Thread {
@Override
public void run() {
while (mRunState) {
lock.lock();
while (mQueue.isEmpty()) {
try {
System.out.println("消费者 - wait");
consumerCondition.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
try {
Thread.sleep(1000);
System.out.println("消费者 - " + mQueue.poll());
producerCondition.signal();
} catch (InterruptedException e) {
e.printStackTrace();
}
lock.unlock();
}
}
}
public static void main(String[] args) {
new ThreadLockTest().start();
}
}
生产者消费者模型
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- 见贤思齐焉,见不贤而内自省也。—《论语》 Java5.0 增加了两种新的容器类型,它们是指:Queue 和 Blo...
- 一、概述 什么是生产者消费者模式生产者消费者模式是通过一个容器来解决生产者和消费者的强耦合问题。生产者和消费者彼此...