在学习java 的多线程中,生产者和消费者的问题是最经典的问题,因此在学习了java的多线程后
本文假设的是只有一个篮子、一个生产者和消费者
首先需要创建一个类Apple(苹果)的类,这个类是产品。
//创建一个苹果类,作为产品
public class Apple{
private int i;
public Apple(int i){
this.i=i;
}
public String toString(){
return "苹果"+i;
}
}
创建一个篮子,其中有装入的方法和取出的方法,都是synchronized的方法,使用synchronized的原因是,不管生产者和消费者都是从一个篮子里来取苹果的,为了避免冲突,采用同步的策略。
//创建一个篮子装苹果
public class Basket{
private Apple[] apples=new Apple[5];
private int index=0;//用来标记篮子里还有多少个Appple
public synchronized void push(Apple apple){
while(index==apples.length){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.notify();
index++;
apples[index]=apple;
}
public synchronized Apple pop(){
while(index==0){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
index--;
return apples[index];
}
}
下面是生产者和消费者类
public class Producer implements Runnable{
private Basket basket;
public Producer(Basket basket){
this.basket=basket;
}
@Override
public void run() {
for(int i=0;i<20;i++){
Apple apple = new Apple(i);
basket.push(apple);
System.out.println("生产了"+apple);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class Consumer implements Runnable{
private Basket basket;//容器
public Consumer(Basket basket){
this.basket=basket;
}
@Override
public void run() {
for(int i=0;i<20;i++){
Apple apple=basket.pop();
System.out.println("消费了"+apple);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
测试类Main
public class Main {
public static void main(String[] args){
Basket basket=new Basket();//容器
Producer producer=new Producer(basket);//生产者
Consumer consumer=new Consumer(basket);//消费者
Thread thread1=new Thread(producer);
Thread thread2=new Thread(consumer);
thread1.start();
thread2.start();
}
}