如下为生产者消费者的最简单的使用方式

    1. public static class InstanceFuture<T> {
    2. private volatile T hz;
    3. private volatile Throwable throwable;
    4. public T get() {
    5. if (hz != null) {
    6. return hz;
    7. }
    8. boolean restoreInterrupt = false;
    9. synchronized (this) {
    10. while (hz == null && throwable == null) {
    11. try {
    12. wait();
    13. } catch (InterruptedException ignored) {
    14. restoreInterrupt = true;
    15. }
    16. }
    17. }
    18. if (restoreInterrupt) {
    19. Thread.currentThread().interrupt();
    20. }
    21. if (hz != null) {
    22. return hz;
    23. }
    24. throw new IllegalStateException(throwable);
    25. }
    26. public void set(T proxy) {
    27. synchronized (this) {
    28. this.hz = proxy;
    29. notifyAll();
    30. }
    31. }
    32. public void setFailure(Throwable throwable) {
    33. synchronized (this) {
    34. this.throwable = throwable;
    35. notifyAll();
    36. }
    37. }
    38. public boolean isSet() {
    39. return hz != null;
    40. }
    41. }

    典型的生产者和消费者模式,中最主要的就是这个相互间交互的这个数据存储部分,而这个存储部分,我觉得我们就可以将这个封装为一个类,然后这个类去做生产者和消费者之间的调度,这样我们就可以先提供接口。

    1. public interface Storage{
    2. void produce();
    3. void consume();
    4. }

    然后在根据顶层接口做抽象类

    1. public class AbstractStorage {
    2. // 锁对象,也可以为当前对象
    3. private Object lock;
    4. // 循环的条件
    5. private boolean condition;
    6. public void produce(int num){
    7. //同步
    8. synchronized (lock){
    9. //当前有的不满足需要,进行等待,直到满足条件
    10. while(condition){
    11. try {
    12. //等待阻塞
    13. lock.wait();
    14. } catch (InterruptedException e) {
    15. e.printStackTrace();
    16. }
    17. }
    18. }
    19. // ...
    20. throw new IllegalStateException(throwable);
    21. }
    22. public void consume() {
    23. synchronized (this) {
    24. this.hz = proxy;
    25. notifyAll();
    26. }
    27. }
    28. }

    参考:
    https://www.cnblogs.com/moongeek/p/7631447.html