zoukankan      html  css  js  c++  java
  • 生产者消费者synchronized wait notify

    package ProduceQueueProduce;

    import java.util.Queue;

    public class ProducerThread extends Thread {
    public static Queue<Object> q;
    private int eleNum =15;
    @Override
    public void run(){
    while(true){
    try {
    Thread.sleep(10);
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    produce();
    }
    }

    private void produce() {
    synchronized(q){
    while(q.size() == eleNum){
    try {
    q.wait();
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    }
    q.add(new Object());
    System.out.println(Thread.currentThread().getName()+"生产者队列大小:"+ q.size());
    q.notifyAll();
    }
    }


    public ProducerThread(String name) {
    super(name);
    }
    }
    package ProduceQueueProduce;

    import java.util.Queue;

    public class ConsumerThread extends Thread {
    public static Queue<Object> q;
    @Override
    public void run(){
    while(true){
    try {
    Thread.sleep(100);
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    consume();
    }
    }

    private void consume() {
    synchronized(q){
    while(q.size() == 0){
    try {
    q.wait();
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    }
    q.remove();
    System.out.println(Thread.currentThread().getName()+"消费者队列大小:"+q.size());
    q.notifyAll();
    }
    }


    public ConsumerThread(String name) {
    super(name);
    }
    }

    package ProduceQueueProduce;

    import java.util.ArrayDeque;
    import java.util.Queue;


    public class Test {
    public static Queue<Object> q = new ArrayDeque<>();
    public static void main(String args[]) throws InterruptedException {
    ConsumerThread c = new ConsumerThread("c");
    ProducerThread p = new ProducerThread("p");
    ProducerThread.q=q;
    ConsumerThread.q = q;
    p.start();
    c.start();

    }
    }





  • 相关阅读:
    别闹了,这些都不是数字化转型
    对不起,“下一代ERP”仍旧是现在的ERP
    这世界真小
    SAP S4HANA 2020 Fully-Activated Appliance 虚拟机版分享
    花费巨资参加SAP培训真的有用吗?
    剑指 Offer 07. 重建二叉树
    剑指 Offer 06. 从尾到头打印链表
    剑指 Offer 05. 替换空格
    剑指 Offer 04.二维数组中的查找
    剑指 Offer 03. 数组中重复的数字
  • 原文地址:https://www.cnblogs.com/mlz-2019/p/9545748.html
Copyright © 2011-2022 走看看