分享:java多线程实现生产者消费者问题
//生产者消费者问题//生产者线程
class ProducerThread extends Thread{
//private final Random random;
private final Table table;
private static int id=0;
public ProducerThread(String name,Table table){
super(name);
this.table=table;
}
public void run(){
try{
while(true){
Thread.sleep(1000);
String cake="产品"+nextId();
table.put(cake);
}
}catch(InterruptedException e){}
}
private static synchronized int nextId(){
return id++;
}
}
//消费者线程
class ConsumerThread extends Thread{
private final Table table;
public ConsumerThread(String name,Table table){
super(name);
this.table=table;
}
public void run(){
try{
while(true){
String cake=table.take();
Thread.sleep(2000);
}
}catch(InterruptedException e){}
}
}
//缓冲池
class Table{
private final String[] buffer;
private int tail;
private int head;
private int count;
public Table(int count){
this.buffer=new String[count];
this.head=0;
this.tail=0;
this.count=0;
}
synchronized void put(String cake)throws InterruptedException{
System.out.println(Thread.currentThread().getName()+" 放入 "+cake);
while(count>=buffer.length){
System.out.println(Thread.currentThread().getName()+" 缓冲池满了,等一等吧...");
wait();
System.out.println(Thread.currentThread().getName()+" 有空间了,开始放...");
}
buffer[tail]=cake;
tail=(tail+1)%buffer.length;
count++;
System.out.println("缓冲池中的产品数---->"+(count+1));
notifyAll();
}
synchronized String take()throws InterruptedException{
while(count<=0){
System.out.println(Thread.currentThread().getName()+" 缓冲池没产品了,等一等吧...");
wait();
System.out.println(Thread.currentThread().getName()+" 有产品了,开吃...");
}
String cake=buffer[head];
head=(head+1)%buffer.length;
count--;
notifyAll();
System.out.println(Thread.currentThread().getName()+" 拿走 "+cake);
System.out.println("缓冲池中的产品数----->"+(count+1));
return cake;
}
}
public class Main {
public static void main(String args[]){
Table table=new Table(10);
new ProducerThread("生产者",table).start();
new ConsumerThread("消费者",table).start();
}
}
可以运行------>多多指正~
----------------解决方案--------------------------------------------------------
程序的优化是没有止境的,能运行出来就行,如果你这个只是交作业的话.如果是真实的系统,你按照客户的需求来好了。
----------------解决方案--------------------------------------------------------
回复 楼主 随WW便
这个比较简单n个生产者
m个消费者
才更实际点
----------------解决方案--------------------------------------------------------
这个很简单啊:
new ProducerThread("生产者1",table).start();
new ProducerThread("生产者2",table).start();
new ProducerThread("生产者3",table).start();
new ProducerThread("生产者4",table).start();
new ProducerThread("生产者5",table).start();
new ConsumerThread("消费者1",table).start();
new ConsumerThread("消费者2",table).start();
new ConsumerThread("消费者3",table).start();
new ConsumerThread("消费者4",table).start();
不就行了
----------------解决方案--------------------------------------------------------