Java多线程之生产者消费者
生产者和消费者的实例:
商品类:
/**
* 商品类
*
*/
public class Goods {
final int MAX_NUMBER = 30; // 最大数量
final int MIN_NUMBER = 0; // 最小数量
private int number;
public Goods(int number) {
super();
this.number = number;
}
public synchronized int getNumber() {
return number;
}
// 添加
public void addNumber() throws InterruptedException{
if(number >= MAX_NUMBER){
wait();
}
synchronized(this){ // 同步代码块
this.number = number + 1;
System.out.println("生产者生产商品,商品数为:" + number);
}
notifyAll();
}
// 减少
public void sumNumber() throws InterruptedException{
if(number <= MIN_NUMBER){
wait();
}
synchronized(this){
this.number = number - 1;
System.out.println("消费者消费商品,商品数为:" + number);
}
notifyAll();
}
}
测试类:
package book_14.synch;
public class Test {
public static void main(String[] args) {
// 创建对象
Goods good = new Goods(20); // 开始的商品数量设为20
while(true){
// 生产者
Runnable r1 = () ->{
try {
while(true){
good.addNumber();
//Thread.sleep(10);
}
} catch (Exception e) {
// TODO: handle exception
}
};
Thread t1 = new Thread(r1);
t1.start();
// 消费者
Runnable r2 = () ->{
try {
while(true){
good.sumNumber();
//Thread.sleep(10);
}
} catch (Exception e) {
// TODO: handle exception
}
};
Thread t2 = new Thread(r2);
t2.start();
}
}
}