利用可重入锁ReentrantLock实现生产者消费者

xiaoxiao2021-02-28  23

import java.text.SimpleDateFormat;

import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.ReentrantLock; public class Test91 { public static void main(String[] args) { Msg msg = new Msg(); new Thread(new Producer(msg)).start(); new Thread(new Consumer(msg)).start(); } } /**  * 消息  * @author TT  *  */ class Msg { final static int MAXQUENE = 10; List<String> msgs = new ArrayList<String>(); //声明可重入锁 ReentrantLock lock = new ReentrantLock(); Condition condition = lock.newCondition(); private void add() { String msg = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()); msgs.add(msg); System.out.println("生产消息--" + msg); } private void sub() { String msg = msgs.remove(0); System.out.println("消费消息--" + msg); } public void consume() { lock.lock(); try { while(msgs.size() == 0) { try { condition.await(); } catch (InterruptedException e) { e.printStackTrace(); } } sub(); condition.signalAll(); } finally { lock.unlock(); } } public void produce() { lock.lock(); try { while(msgs.size() == 10) { try { condition.await(); } catch (InterruptedException e) { e.printStackTrace(); } } add(); condition.signalAll(); } finally { lock.unlock(); } } } /**  * 消费者  * @author TT  *  */ class Consumer implements Runnable { private Msg msg; Consumer(Msg msg) { this.msg = msg; } @Override public void run() { while(true) { msg.consume(); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } } /**  * 生产者  * @author TT  *  */ class Producer implements Runnable { private Msg msg; Producer(Msg msg) { this.msg = msg; } @Override public void run() { while(true) { msg.produce(); try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } } }
转载请注明原文地址: https://www.6miu.com/read-2626392.html

最新回复(0)