您好,登錄后才能下訂單哦!
今天就跟大家聊聊有關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 List<Product>products=new LinkedList<Product>(); 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項目中的生產者消費者如何利用多線程實現有進一步的了解嗎?如果還想了解更多知識或者相關內容,請關注億速云行業資訊頻道,感謝大家的支持。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。