多线程模拟生产者消费者示例之Lock
2021-06-15 14:06
} /** @Override } catch (InterruptedException e) { @Override /**
}
* 生产者
*/
class PThread implements Runnable {
private List
private LockEntity lockEntity;
private AtomicInteger integer = new AtomicInteger();
public PThread(List
this.list = list;
this.lockEntity = lockEntity;
}
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(); //等待
}
e.printStackTrace();
} finally {
lockEntity.lock.unlock();
}
}
}
}
class CThread implements Runnable {
private List
private LockEntity lockEntity;
public CThread(List
this.list = list;
this.lockEntity = lockEntity;
}
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();
}
下一篇:js回到顶部动画效果实现方法
文章标题:多线程模拟生产者消费者示例之Lock
文章链接:http://soscw.com/index.php/essay/94192.html