자바 다 중 스 레 드 생산자 소비자 모델 실현 과정 분석
예시:
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()로 바 꾸 면 된다.
이상 이 바로 본 고의 모든 내용 입 니 다.여러분 의 학습 에 도움 이 되 고 저 희 를 많이 응원 해 주 셨 으 면 좋 겠 습 니 다.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
JPA + QueryDSL 계층형 댓글, 대댓글 구현(2)이번엔 전편에 이어서 계층형 댓글, 대댓글을 다시 리팩토링해볼 예정이다. 이전 게시글에서는 계층형 댓글, 대댓글을 구현은 되었지만 N+1 문제가 있었다. 이번에는 그 N+1 문제를 해결해 볼 것이다. 위의 로직은 이...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.