如下为生产者消费者的最简单的使用方式
public static class InstanceFuture<T> {
private volatile T hz;
private volatile Throwable throwable;
public T get() {
if (hz != null) {
return hz;
}
boolean restoreInterrupt = false;
synchronized (this) {
while (hz == null && throwable == null) {
try {
wait();
} catch (InterruptedException ignored) {
restoreInterrupt = true;
}
}
}
if (restoreInterrupt) {
Thread.currentThread().interrupt();
}
if (hz != null) {
return hz;
}
throw new IllegalStateException(throwable);
}
public void set(T proxy) {
synchronized (this) {
this.hz = proxy;
notifyAll();
}
}
public void setFailure(Throwable throwable) {
synchronized (this) {
this.throwable = throwable;
notifyAll();
}
}
public boolean isSet() {
return hz != null;
}
}
典型的生产者和消费者模式,中最主要的就是这个相互间交互的这个数据存储部分,而这个存储部分,我觉得我们就可以将这个封装为一个类,然后这个类去做生产者和消费者之间的调度,这样我们就可以先提供接口。
public interface Storage{
void produce();
void consume();
}
然后在根据顶层接口做抽象类
public class AbstractStorage {
// 锁对象,也可以为当前对象
private Object lock;
// 循环的条件
private boolean condition;
public void produce(int num){
//同步
synchronized (lock){
//当前有的不满足需要,进行等待,直到满足条件
while(condition){
try {
//等待阻塞
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
// ...
throw new IllegalStateException(throwable);
}
public void consume() {
synchronized (this) {
this.hz = proxy;
notifyAll();
}
}
}