栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

多线程——生产者和消费者模式

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

多线程——生产者和消费者模式

生产者 

package com.ProductCusromer.method3;

import java.util.concurrent.BlockingQueue;


public class Product4 implements Runnable {
    private BlockingQueue queue;
    private String name;
    public Product4(String name, BlockingQueue queue) {
        this.queue = queue;
        this.name = name;
    }
    @Override
    public void run() {
        while(true){
            try {
                int val = (int) Math.random();
                queue.put(val);
                System.out.println(name + "生产:"+val+".当前队列长度:"+ queue.size());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

消费者

package com.ProductCusromer.method3;

import java.util.concurrent.BlockingDeque;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;


public class Consumer4 implements Runnable{
    private BlockingQueue queue;
    private String name;
    public Consumer4(String name, BlockingQueue queue) {
        this.queue = queue;
        this.name = name;
    }
    @Override
    public void run() {
        try {
            while (true){
                int val = (int) queue.take();
                System.out.println(name + "消费:"+val+".当前队列长度:"+ queue.size());
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

package com.ProductCusromer.method3;

import com.ProductCusromer.method1.Consumer1;
import com.ProductCusromer.method1.Product1;

import javax.persistence.criteria.CriteriaBuilder;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.linkedBlockingDeque;
import java.util.concurrent.linkedBlockingQueue;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;


public class Main {
    public static void main(String[] args) {
        BlockingQueue queue = new linkedBlockingQueue<>(20);
        Product4 producer1 = new Product4("生产1号", queue);
        Product4 producer2 = new Product4("生产2号", queue);
        Product4 producer3 = new Product4("生产3号", queue);

        Consumer4 consumer1 = new Consumer4("消费1号", queue);
        Consumer4 consumer2 = new Consumer4("消费2号", queue);

// 开始producer线程进行生产
        new Thread(producer1).start();
        new Thread(producer2).start();
        new Thread(producer3).start();

// 开始consumer线程进行消费。
        new Thread(consumer1).start();
        new Thread(consumer2).start();
    }
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/531471.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号