JAVA项目中的生产者消费者如何利用多线程实现
今天就跟大家聊聊有关JAVA项目中的生产者消费者如何利用多线程实现,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。
成都创新互联专注于姑苏网站建设服务及定制,我们拥有丰富的企业做网站经验。 热诚为您提供姑苏营销型网站建设,姑苏网站制作、姑苏网页设计、姑苏网站官网定制、微信小程序服务,打造姑苏网络公司原创品牌,更为您提供姑苏网站排名全网营销落地服务。
JAVA多线程实现生产者消费者的实例详解
Product.Java
package consumerProducer; public class Product { private String id; public String getId() { return id; } public void setId(String id) { this.id = id; } public Product(String id) { this.id=id; } public String toString() { return "product "+id; } }
Pool.java
package consumerProducer; import java.util.*; public class Pool { private int number=0; private Listproducts=new LinkedList (); public int getNumber() { return number; } public void setNumber(int number) { this.number = number; } public synchronized Product consumeProduct(){ //可以去掉synchronized关键字 if(products.size()>0) { Product p= products.get(0); products.remove(0); number--; return p; } else return null; } public synchronized void addProduct(Product p){ //可以去掉synchronized关键字 products.add(p); number++; } }
Consumer.java
package consumerProducer; public class Consumer implements Runnable { private String id; Pool pool; public Consumer(String id,Pool pool) { this.id=id; this.pool=pool; } @Override public void run() { while(!Thread.currentThread().interrupted()) { Product product=null; synchronized(pool){ while(pool.getNumber()<=0)//生产不足 { try { pool.wait();//生产者等待 } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } product=pool.consumeProduct(); } System.out.println("consuming "+id+product.toString()); try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
Producer.java
package consumerProducer; public class Producer implements Runnable{ private int i_p=0; private String id; Pool pool; int i=0; public Producer(String id ,Pool pool) { this.id=id; this.pool=pool; } public Product createProduct() { return new Product(String.valueOf(++i_p)); } @Override public void run() { // TODO Auto-generated method stub while(!Thread.currentThread().interrupted()) { Product p=new Product(String.valueOf(++i_p)); try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } synchronized(pool) { pool.addProduct(p); System.out.println("producer "+id+" adding product...."+p.toString()); pool.notifyAll(); } } } }
Main.java
package consumerProducer; public class Main { public static void main(String[] args) { // TODO Auto-generated method stub Pool pool=new Pool(); for(int i=0;i<5;i++) { Thread consumer=new Thread(new Consumer("consumer "+i,pool)); Thread producer=new Thread(new Producer("producer "+i,pool)); consumer.start(); producer.start(); } } }
看完上述内容,你们对JAVA项目中的生产者消费者如何利用多线程实现有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注创新互联行业资讯频道,感谢大家的支持。
本文名称:JAVA项目中的生产者消费者如何利用多线程实现
URL地址:http://myzitong.com/article/jhpgge.html