• 简单生产者消费者模式


    知识点:线程基本通信

    生产者:
    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();

    }
  • 相关阅读:
    关于明确我校教学作息时间的通知
    放假时间
    五一上课表
    课表
    mysql 数据库备份与还原
    默默的追随
    2004上半年
    IE慢吗?
    创建的permission java.security.AllPermission;文件,用于加密
    数据库驱动
  • 原文地址:https://www.cnblogs.com/coderdxj/p/9708074.html
Copyright © 2020-2023  润新知