zoukankan      html  css  js  c++  java
  • 多线程模拟生产者消费者示例之wait/notify

    public class Test {

    public static void main(String[] args) throws InterruptedException {
    List<String> queue = new ArrayList<>();
    new Thread(new PThread(queue)).start();
    new Thread(new CThread(queue)).start();
    }
    }

    /**
    * 生产者
    */
    class PThread implements Runnable {
    private List<String> queue;
    private AtomicInteger i = new AtomicInteger();

    public PThread(List<String> queue) {
    this.queue = queue;
    }

    @Override
    public void run() {
    while (true) {
    synchronized(queue){
    //如果queue有元素,那么就释放锁吧
    if (queue.size() == 1) {
    try {
    queue.wait();// 释放锁
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    } else { //没有元素就生产一个元素
    try {
    Thread.sleep(1000);
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    String data = i.getAndIncrement() + "";
    queue.add(data);
    System.out.println("生产者线程,生产一个元素:"+data);
    queue.notify(); //唤醒本线程,就可以获取锁了
    }
    }
    }
    }
    }

    /**
    * 消费者
    */
    class CThread implements Runnable {
    private List<String> queue;

    public CThread(List<String> queue) {
    this.queue = queue;
    }

    @Override
    public void run() {
    while (true) {
    synchronized (queue) {
    //如果queue中没有元素,就释放锁,让生产者去生产
    if (queue.size() == 0) {
    try {
    queue.wait(); //就释放锁
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    } else { //消费元素
    String data = queue.remove(0);
    System.out.println("消费者线程,消费一个元素:"+data);
    queue.notify();
    }
    }
    }
    }
    }
     

         

  • 相关阅读:
    转载Crazybingo的文章: 第三章 创造平台——Quartus II 11.0 套件安装指南
    Can't launch the ModelSim-Altera software
    一种简单的ADV7842调试视频pixel_cnt/line的办法.
    调试ADV7842的点滴 之 hdmi
    沿检测使能,时钟同步化
    global clock network
    捡到篮子里边的都是菜
    (转)时序分析基本公式
    Spring中的AOP(一)
    AOP的概念
  • 原文地址:https://www.cnblogs.com/z-qinfeng/p/9728702.html
Copyright © 2011-2022 走看看