您好,欢迎访问一九零五行业门户网

Java中消费者问题的代码分析

本篇文章给大家带来的内容是关于java中消费者问题的代码分析,有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。
1.资源public class resource { //当前资源的数量 int num = 0; //当前资源的上限 int size = 10; //消费资源 public synchronized void remove() { //如果num为0,没有资源了,需要等待 while (num == 0) { try { system.out.println("消费者进入等待"); this.wait(); } catch (interruptedexception e) { e.printstacktrace(); } } //如果线程可以执行到这里,说明资源里有资源可以消费 num--; system.out.println("消费者线程为:" + thread.currentthread().getname() + "--资源数量:" + num); this.notifyall(); } //生产资源 public synchronized void put() { //如果资源满了,就进入阻塞状态 while (num == size) { try { system.out.println("生产者进入等待"); this.wait(); } catch (interruptedexception e) { e.printstacktrace(); } } num++; system.out.println("生产者线程为:" + thread.currentthread().getname() + "--资源数量:" + num); this.notifyall(); }}
2.消费者public class consumer implements runnable { private resource resource; public consumer(resource resource) { this.resource = resource; } @override public void run() { while (true){ resource.remove(); } }}
3.生产者public class producer implements runnable { private resource resource; public producer(resource resource){ this.resource=resource; } @override public void run() { while (true){ resource.put(); } }}
4.测试public class testconsumerandproducer { public static void main(string[] args) { resource resource = new resource(); //生产线程 producer p1 = new producer(resource); //消费线程 consumer c1 = new consumer(resource); new thread(p1).start(); new thread(c1).start(); }}
相关推荐:
关于java生产者与消费者的实例详解
java多线程之并发协作生产者消费者设计模式
以上就是java中消费者问题的代码分析的详细内容。
其它类似信息

推荐信息