zoukankan      html  css  js  c++  java
  • 简单生产者消费者模式

    知识点:线程基本通信

    生产者:
    package com.fengunion.dxc.pc;

    import java.util.List;

    public class Producer implements Runnable {

    private List<String> list;

    public Producer(List<String> list) {
    this.list = list;
    }

    @Override
    public void run() {
    while (true){
    synchronized (list){
    if(list.size()==1){
    System.out.println("队列已满....");
    try {
    list.wait();
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    }
    list.add("1");
    list.forEach(x ->{
    System.out.println("生产数据:"+x);
    });
    list.notify();
    }
    }
    }
    }
    消费者:
    package com.fengunion.dxc.pc;

    import java.util.List;

    public class Consumer implements Runnable {
    private List<String> list;
    public Consumer(List<String> list){
    this.list=list;
    }
    @Override
    public void run() {
    while (true){
    synchronized (list){
    if(list.size()==0){
    System.out.println("队列为空");
    try {
    list.wait();
    } catch (InterruptedException e) {
    e.printStackTrace();
    }

    }
    list.forEach(x ->{
    System.out.println("消费数据:"+x);
    });
    list.remove("1");
    list.notify();
    }
    }
    }
    }
    测试:
    public static void main(String[] args) {
    List<String> list=new ArrayList<>();
    Producer p=new Producer(list);
    Consumer c = new Consumer(list);
    Thread thread = new Thread(p);
    Thread thread1 = new Thread(c);
    thread.start();
    thread1.start();

    }
  • 相关阅读:
    HTML5 模板推荐
    OpenCV初探
    微信开放框架-UCToo
    ProFTPD 初探
    移动开发者服务平台-友盟
    线程原理理解
    JVM参数及性能调优
    GC——垃圾回收
    JVM内存模型
    php常用 随机数
  • 原文地址:https://www.cnblogs.com/coderdxj/p/9708074.html
Copyright © 2011-2022 走看看