首页 > 其他分享 >手写消费者生产者

手写消费者生产者

时间:2024-05-06 22:33:32浏览次数:18  
标签:tickets 消费者 生产者 lock isEmpty isFull 手写 public Condition

生产者

import java.util.List;
import java.util.Random;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class ProducerThread implements Runnable {

    private String threadName;

    private ReentrantLock lock;

    private Condition isFull;

    private Condition isEmpty;

    private List<String> tickets;
    @Override
    public void run() {
        while (true) {
            if (!lock.tryLock()) {
                continue;
            }

            try {
                if (tickets.size() >= 10) {
                    isFull.await();
                    continue;
                }
                Random random = new Random();

                String ticketName = "门票" + random.nextInt(10);
                tickets.add(ticketName);
                System.out.println("[" + Thread.currentThread().getName() + "]生产:" + ticketName);
                isEmpty.signalAll();
            } catch (Exception ex) {
                ex.printStackTrace();
            } finally {
                lock.unlock();
            }
        }
    }

    public String getThreadName() {
        return threadName;
    }

    public void setThreadName(String threadName) {
        this.threadName = threadName;
    }

    public ReentrantLock getLock() {
        return lock;
    }

    public void setLock(ReentrantLock lock) {
        this.lock = lock;
    }

    public Condition getIsFull() {
        return isFull;
    }

    public void setIsFull(Condition isFull) {
        this.isFull = isFull;
    }

    public Condition getIsEmpty() {
        return isEmpty;
    }

    public void setIsEmpty(Condition isEmpty) {
        this.isEmpty = isEmpty;
    }

    public List<String> getTickets() {
        return tickets;
    }

    public void setTickets(List<String> tickets) {
        this.tickets = tickets;
    }

}

 

消费者

import java.util.List;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class ConsumerThread implements Runnable {

    private String threadName;

    private ReentrantLock lock;

    private Condition isFull;

    private Condition isEmpty;

    private List<String> tickets;

    @Override
    public void run() {
        while (true) {
            if (!lock.tryLock()) {
                continue;
            }

            try {
                if (tickets.size() == 0) {
                    isEmpty.await();
                    continue;
                }
                int index = tickets.size() - 1;
                String ticketName = tickets.get(index);
                tickets.remove(index);
                System.out.println("[" + Thread.currentThread().getName() + "]消费:" + ticketName);
                isFull.signalAll();
            } catch (Exception ex) {
                ex.printStackTrace();
            } finally {
                lock.unlock();
            }
        }
    }

    public String getThreadName() {
        return threadName;
    }

    public void setThreadName(String threadName) {
        this.threadName = threadName;
    }

    public ReentrantLock getLock() {
        return lock;
    }

    public void setLock(ReentrantLock lock) {
        this.lock = lock;
    }

    public Condition getIsFull() {
        return isFull;
    }

    public void setIsFull(Condition isFull) {
        this.isFull = isFull;
    }

    public Condition getIsEmpty() {
        return isEmpty;
    }

    public void setIsEmpty(Condition isEmpty) {
        this.isEmpty = isEmpty;
    }

    public List<String> getTickets() {
        return tickets;
    }

    public void setTickets(List<String> tickets) {
        this.tickets = tickets;
    }

}

 

测试类

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class TicketMain {

    static List<ProducerThread> producerThreads = new ArrayList<>();
    static List<ConsumerThread> consumerThreads = new ArrayList<>();

    static ReentrantLock lock = new ReentrantLock();
    static Condition isFull = lock.newCondition();
    static Condition isEmpty = lock.newCondition();
    static volatile List<String> tickets = new ArrayList<>();

    static {
        for (int i = 0; i < 10; i++) {
            ProducerThread producerThread = new ProducerThread();
            producerThread.setThreadName("生产者" + i);
            producerThread.setLock(lock);
            producerThread.setIsEmpty(isEmpty);
            producerThread.setIsFull(isFull);
            producerThread.setTickets(tickets);
            producerThreads.add(producerThread);
        }
        for (int i = 0; i < 10; i++) {
            ConsumerThread consumerThread = new ConsumerThread();
            consumerThread.setThreadName("消费者" + i);
            consumerThread.setLock(lock);
            consumerThread.setIsEmpty(isEmpty);
            consumerThread.setIsFull(isFull);
            consumerThread.setTickets(tickets);
            consumerThreads.add(consumerThread);
        }

    }

    public static void main(String[] args) {
        producerThreads.stream().forEach(e->{
            Thread thread = new Thread(e);
            thread.setName(e.getThreadName());
            thread.start();
        });
        consumerThreads.stream().forEach(e->{
            Thread thread = new Thread(e);
            thread.setName(e.getThreadName());
            thread.start();
        });
    }
}

 

标签:tickets,消费者,生产者,lock,isEmpty,isFull,手写,public,Condition
From: https://www.cnblogs.com/use-D/p/17869184.html

相关文章

  • MyBatis学习总结 + 【手写MyBatis底层机制核心】
    MyBatis笔记MyBatis介绍MyBatis是一个持久层框架前身是ibatis,在ibatis3.x时,更名为MyBatisMyBatis在java和sql之间提供更灵活的映射方案mybatis可以将对数据表的操作(sql,方法)等等直接剥离,写到xml配置文件,实现和java代码的解耦mybatis通过SQL操作DB,建库建表......
  • 手写Spring框架
    1.手写Spring框架@目录1.手写Spring框架每博一文案2.反射机制的回顾3.开始手写Spring框架3.1第一步:使用IDE创建模块myspring3.2第二步:准备好我们要管理的Bean3.3第三步:准备myspring.xml配置文件3.4第四步:编写ApplicationContext接口3.5第五步:编写ClassPathXmlApplic......
  • 手写MVVM
    internalclassDelegateCommand:ICommand{publiceventEventHandler?CanExecuteChanged{add{CommandManager.RequerySuggested+=value;}remove{CommandManager.RequerySuggested-=value;}}publicDelegateComm......
  • kafka消费者提交方式(代码演示)
    自动提交,手动提交(异步提交,同步提交,异步同步结合提交),原理:提交后,重新消费消息位移发生变化。1publicclassMyConsumer{23privatestaticKafkaConsumer<String,String>consumer;4privatestaticPropertiesproperties;56static{7......
  • 从零手写实现 apache Tomcat-01-入门介绍
    创作缘由平时使用tomcat等web服务器不可谓不多,但是一直一知半解。于是想着自己实现一个简单版本,学习一下tomcat的精髓。怎么实现一个tomcat呢?Tomcat就像是一个用Java语言搭起来的大舞台,专门用来演出那些用Java编写的网页剧。想要玩得转Tomcat,你最好对Java语言有所了解......
  • RocketMQ生产者启动源码
    核心代码初始化Default生产者DefaultMQProducerproducer=newDefaultMQProducer(PRODUCER_GROUP);设置NameAddr地址producer.setNamesrvAddr(DEFAULT_NAMESRVADDR);producer.start();分析newDefaultMQProducer(PRODUCER_GROUP)publicDefaultMQProducer(finalStringp......
  • 实验16-使用GAN生成手写数字样本
    版本python3.7tensorflow版本为tensorflow-gpu版本2.6运行结果: 代码:from__future__importprint_function,divisionfromkeras.datasetsimportmnistfromkeras.layersimportInput,Dense,Reshape,Flatten,Dropoutfromkeras.layersimportBatchNormalizatio......
  • 实验14-1使用cnn完成MNIST手写体识别(tf)+实验14-2使用cnn完成MNIST手写体识别(keras)
    版本python3.7tensorflow版本为tensorflow-gpu版本2.6实验14-1使用cnn完成MNIST手写体识别(tf)运行结果: 代码:importtensorflowastf#Tensorflow提供了一个类来处理MNIST数据fromtensorflow.examples.tutorials.mnistimportinput_dataimporttime#载入数据集mn......
  • RabbitMQ处理消费者过载的策略
    RabbitMQ的消费者过载指的是在RabbitMQ消息队列系统中,消费者(即处理消息的应用程序或进程)无法及时处理从队列中接收到的消息,导致消息在队列中积压,进而可能引发系统性能下降、延迟增加或甚至系统崩溃等问题。引起消费者过载的原因:高负载产生的流量:当生产者向RabbitMQ发送大量消息......
  • 手写bind函数
    今天无事手写一个bind函数//重写bind函数Function.prototype.bindDemo=function(){//arguments可以获取到传的参数//1.先把获取到的数据转换为数组的格式letargs=Array.prototype.slice.call(arguments);//2.获取数组中第一个元素,即this即将指向的数据le......