자바 다 중 스 레 드 생산자 소비자 모델 실현 과정 분석

단일 생산자 와 단일 소비자
예시:

public class ProduceConsume {
    public static void main(String[] args) {
      String lock = new String("");
      Produce produce = new Produce(lock);
      Consume consume = new Consume(lock);

      new Thread(() -> {
        while (true) {
          produce.setValue();
        }
      }, "ProductThread").start();
      new Thread(() -> {
        while (true) {
          consume.getValue();
        }
      }, "ConsumeThread").start();
    }

    /**
     *    
     */
    static class Produce {
      private String lock;

      public Produce(String lock) {
        this.lock = lock;
      }

      public void setValue() {
        try {
          synchronized (lock) {
            if (!ValueObject.value.equals("")) {
              lock.wait();
            }
            String value = System.currentTimeMillis() + "_" + System.nanoTime();
            System.out.println("set   " + value);
            ValueObject.value = value;
            lock.notify();
          }
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
      }
    }

    /**
     *    
     */
    static class Consume {
      private String lock;

      public Consume(String lock) {
        this.lock = lock;
      }

      public void getValue() {
        try {
          synchronized (lock) {
            if (ValueObject.value.equals("")) {
              lock.wait();
            }
            System.out.println("get   " + ValueObject.value);
            ValueObject.value = "";
            lock.notify();
          }
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
      }
    }

    static class ValueObject {
      public static String value = "";
    }
}
실행 결 과 는 다음 과 같 습 니 다.

다 생산자 와 다 소비자
이런 모델 에서'가사',즉 모든 스 레 드 가 WAITNG 상태 에 들 어 갔 고 프로그램 이 어떠한 업무 기능 도 수행 하지 않 으 며 전체 프로젝트 가 정지 상태 에 있다.
예시:

public class MultiProduceConsume {
  public static void main(String[] args) throws InterruptedException {
    String lock = new String("");
    Produce produce = new Produce(lock);
    Consume consume = new Consume(lock);
    Thread[] pThread = new Thread[2];
    Thread[] cThread = new Thread[2];
    for (int i = 0; i < 2; i++) {
      pThread[i] = new Thread(() -> {
        while (true) {
          produce.setValue();
        }
      }, "   " + (i + 1));

      cThread[i] = new Thread(() -> {
        while (true) {
          consume.getValue();
        }
      }, "   " + (i + 1));
      pThread[i].start();
      cThread[i].start();
    }

    Thread.sleep(5000);
    Thread[] threadArray = new Thread[Thread.currentThread().getThreadGroup().activeCount()];
    Thread.currentThread().getThreadGroup().enumerate(threadArray);
    for (int i = 0; i < threadArray.length; i++) {
      System.out.println(threadArray[i].getName() + " " + threadArray[i].getState());
    }
  }

  static class Produce {
    private String lock;

    public Produce(String lock) {
      this.lock = lock;
    }

    public void setValue() {
      try {
        synchronized (lock) {
          while(!ValueObject.value.equals("")) {
            System.out.println("    " + Thread.currentThread().getName() + " WAITING ⭐");
            lock.wait();
          }
          System.out.println("    " + Thread.currentThread().getName() + " RUNNABLE ");
          String value = System.currentTimeMillis() + "_" + System.nanoTime();
          ValueObject.value = value;
          lock.notify();
        }
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }
  }

  static class Consume {
    private String lock;

    public Consume(String lock) {
      this.lock = lock;
    }

    public void getValue() {
      try {
        synchronized (lock) {
          while (ValueObject.value.equals("")) {
            System.out.println("    " + Thread.currentThread().getName() + " WAITING ⭐");
            lock.wait();
          }
          System.out.println("    " + Thread.currentThread().getName() + "RUNNABLE ");
          ValueObject.value = "";
          lock.notify();
        }
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }
  }

  static class ValueObject {
    public static String value = "";
  }
}
실행 결 과 는 그림 과 같 습 니 다.

분석:
코드 에서 wait/notify 를 통 해 통신 을 했 지만 notify 가 깨 우 는 것 이 반드시 다른 종류 일 수도 있 고 같은 종류 일 수도 있 습 니 다.예 를 들 어'생산자'가'생산자'와 같은 상황 을 깨 웠 습 니 다.
해결 방안:
가사 가 나타 난 주요 원인 은 동 류 를 연속적으로 깨 울 수 있 기 때문이다.그래서 해결 방안 은 간단 하 다.바로 notify()를 notify All()로 바 꾸 면 된다.
이상 이 바로 본 고의 모든 내용 입 니 다.여러분 의 학습 에 도움 이 되 고 저 희 를 많이 응원 해 주 셨 으 면 좋 겠 습 니 다.

좋은 웹페이지 즐겨찾기