生产者消费者模式是学习线程同步的一个经典案例,主要运用了synchronized关键词,以及object的wait与notify方法
synchronized有两种用法:
1>public sychronized void product(){}
这是同步方法,它的锁对象默认指向this 简单的来说就是如果我创建一个对象,new一片空间,那么他就指向这篇空间,所以例如:
Student s1 = new Student();
Student s2 = new Student();
当s1、s2同时调用以上方法式就无法进行方法同步,因为他们各自有各自的空间,那么我们就应该采用第二种方法
2>synchronized(""){}
第二种方法叫做同步块 ()里面的参数是一个object类型 {}里面是需要同步的方法 这样指定锁对象后,就可以解决上面问题了
好了 ,下面我们开始实现生产者消费者模式
本次案例需要创建四个包、分别为 :实体、方法、线程、测试
首先创建实体:
package com.hellojava.entity;
import java.io.Serializable;
public class Good implements Serializable {
private int goodId;
private String goodName;
public int getGoodId() {
return goodId;
}
public void setGoodId(int goodId) {
this.goodId = goodId;
}
public String getGoodName() {
return goodName;
}
public void setGoodName(String goodName) {
this.goodName = goodName;
}
@Override
public String toString() {
return "Good{" +
"goodId=" + goodId +
", goodName='" + goodName + '\'' +
'}';
}
}
然后创建方法类:
package com.hellojava.operation;
import com.hellojava.entity.Good;
import java.util.Stack;
public class GoodOperation {
private Stack<Good> coll = new Stack<>();
private int max = 10;
private int i = 1;
public synchronized void product(){
if(i>max) {
this.notify();
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Good good = new Good();
good.setGoodId(i);
good.setGoodName("商品"+i);
System.out.println("生产了商品:"+good);
i++;
coll.add(good);
}
public synchronized void consume(){
if (i<=1){
this.notify();
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Good good = coll.pop();
System.out.println("出售了商品:"+good);
i--;
}
}
再创建线程,线程分为生产线程和消费线程:
package com.hellojava.thread;
import com.hellojava.operation.GoodOperation;
public class ProductThread extends Thread {
private GoodOperation goodOperation;
public ProductThread(GoodOperation goodOperation){
this.goodOperation = goodOperation;
}
@Override
public void run() {
while(true){
this.goodOperation.product();
}
}
}
package com.hellojava.thread;
import com.hellojava.operation.GoodOperation;
public class ConsumeThread extends Thread {
private GoodOperation goodOperation;
public ConsumeThread(GoodOperation goodOperation){
this.goodOperation = goodOperation;
}
@Override
public void run() {
while (true){
this.goodOperation.consume();
}
}
}
最后进行测试:
package com.hellojava.test;
import com.hellojava.operation.GoodOperation;
import com.hellojava.thread.ConsumeThread;
import com.hellojava.thread.ProductThread;
public class Run {
public static void main(String[] args) {
GoodOperation goodOperation = new GoodOperation();
ProductThread productThread = new ProductThread(goodOperation);
ConsumeThread consumeThread = new ConsumeThread(goodOperation);
productThread.start();
consumeThread.start();
}
}
小结:
生产者消费者模式的关键在于方法类对方法的实现,还有就是合理使用wait与notify方法对线程的运行条件进行控制。