分享: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();
}
}
可以运行------>多多指正~