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();

    }
    }





  • 相关阅读:
    hdu 1542 Atlantis
    cf C. Cupboard and Balloons
    cf C. Tourist Problem
    hdu 4027 Can you answer these queries?
    hdu 1255 覆盖的面积
    hdu 1698 Just a Hook
    zoj 1610 Count the Colors
    hdu 4302 Holedox Eating
    hdu 4288 Coder
    tsne理论学习
  • 原文地址:https://www.cnblogs.com/mlz-2019/p/9545748.html
Copyright © 2011-2022 走看看