• 生产者消费者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();

    }
    }





  • 相关阅读:
    [转]Connecting To SQLite Database Using Node.js
    [转]Ubuntu安装ss客户端
    ubuntu18.04连接pptpd服务器(未成功)
    ubuntu18.04安装DB2 11.1 Express-c
    ubuntu 18.04使用sysbench测试MySQL性能
    ubuntu18.04手动安装二进制MySQL8.0
    ubuntu 18.04下载mysql8.0.13源码并编译安装(暂时没有成功)
    Linux使用sleep进行延迟实验
    『浅入浅出』MySQL 和 InnoDB
    『浅入深出』MySQL 中事务的实现
  • 原文地址:https://www.cnblogs.com/mlz-2019/p/9545748.html
Copyright © 2020-2023  润新知