JAVA多线程实现生产者消费者的实例详解
程序员文章站
2023-12-20 18:22:04
java多线程实现生产者消费者的实例详解
下面的代码实现了生产者消费者的问题
product.java
package consumerproducer;...
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(); } } }
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!