多线程模拟生产者消费者示例之Lock
Posted z-qinfeng
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了多线程模拟生产者消费者示例之Lock相关的知识,希望对你有一定的参考价值。
public class Test {
public static void main(String[] args) {
List<String> list = new ArrayList<>(1);
LockEntity lockEntity = new LockEntity();
new Thread(new PThread(list, lockEntity)).start();
new Thread(new CThread(list, lockEntity)).start();
}
}
/**
* 生产者
*/
class PThread implements Runnable {
private List<String> list;
private LockEntity lockEntity;
private AtomicInteger integer = new AtomicInteger();
public PThread(List<String> list, LockEntity lockEntity) {
this.list = list;
this.lockEntity = lockEntity;
}
@Override
public void run() {
while (true) {
try {
Thread.sleep(1000);
//上锁
lockEntity.lock.lock();
if (lockEntity.flag) {
String data = integer.getAndIncrement() + "";
list.add(data);
System.out.println("生产者线程,生产一个数据:" + data);
lockEntity.flag = false;
lockEntity.condition.signal(); //唤醒
} else {
lockEntity.condition.await(); //等待
}
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lockEntity.lock.unlock();
}
}
}
}
class CThread implements Runnable {
private List<String> list;
private LockEntity lockEntity;
public CThread(List<String> list, LockEntity lockEntity) {
this.list = list;
this.lockEntity = lockEntity;
}
@Override
public void run() {
while (true) {
try {
lockEntity.lock.lock();
if (!lockEntity.flag) {
String data = list.remove(0);
System.out.println("消费者线程,消费了一个数据:" + data);
lockEntity.flag = true;
lockEntity.condition.signal();
} else {
lockEntity.condition.await();
}
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lockEntity.lock.unlock();
}
}
}
}
/**
* 封装锁等信息
*/
class LockEntity {
public boolean flag = true;
public Lock lock = new ReentrantLock();
Condition condition = lock.newCondition();
}
以上是关于多线程模拟生产者消费者示例之Lock的主要内容,如果未能解决你的问题,请参考以下文章