操作系统多线程例子--生产者与消费者

xiaoxiao2021-02-28  111

import java.util.concurrent.locks.*; public class ProducerandConsumer { private static int count = 0; private final int FULL = 100;// 定义最多生产100个 private int flag = 0;// 生产者消费者切换标志 Lock lock = new ReentrantLock();// 创建一个锁对象。 Condition producer_lock = lock.newCondition(); // 生产者监视器 Condition consumer_lock = lock.newCondition(); // 消费者监视器 class Producer implements Runnable { public void run() { while (true) { lock.lock(); try { Thread.sleep(500); } catch (Exception e) { e.printStackTrace(); } try { while ((count == FULL) || (flag == 1)) { try { producer_lock.await(); } catch (Exception e) { e.printStackTrace(); } } count++; flag = 1; System.out.println(Thread.currentThread().getName() + "生产者生产 " + count); consumer_lock.signal(); } finally { lock.unlock(); } } } } class Consumer implements Runnable { public void run() { while (true) { lock.lock(); try { Thread.sleep(500); } catch (InterruptedException e1) { e1.printStackTrace(); } try { while ((count == 0) || (flag == 0)) { try { consumer_lock.await(); } catch (Exception e) { } } System.out.println(Thread.currentThread().getName() + "消费者消费 " + count); if (count == FULL) // 重新从1开始生产消费 { count = 0; } flag = 0; producer_lock.signal(); } finally { lock.unlock(); } } } } public static void main(String[] args) throws Exception { ProducerandConsumer pc = new ProducerandConsumer(); // 生产者 new Thread(pc.new Producer()).start(); // 消费者 new Thread(pc.new Consumer()).start(); } }

 

转载请注明原文地址: https://www.6miu.com/read-41721.html

最新回复(0)