클라이언트의 호출 (서버의 엔드 포인트 중 하나에서)을 폴링하고 클라이언트 메소드가 getStatus
메소드를 구현하도록하고, run 메소드 내부의 상태를 업데이트합니다. 소비자 스레드에 대한, 원유 구현은 같을 것이다 :
public class ConsumerThread implements Runnable{
private int status = 0;
private Random rand = new Random();
private final CountDownLatch startSignal;
public ConsumerThread(CountDownLatch latch){
this.startSignal = latch;
}
public int getStatus() {
return status;
}
private void setStatus(int status) {
this.status = status;
}
public void run() {
try {
this.startSignal.await();
while (true){
this.setStatus(rand.nextInt(10));
}
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}
}
그런 다음 간단한 기본 방법을 시도
(나는 같은 시간에 시작하는 내 모든 스레드를 위해
CountDownLatch을 구현, 그렇지 않은 필수입니다) :
public class ThreadMain{
private static List<ConsumerThread> consumers = new ArrayList<ConsumerThread>();
public static void main(String[] args) {
int NUM_THREAD = 15;
ExecutorService executor = Executors.newFixedThreadPool(NUM_THREAD);
CountDownLatch latch = new CountDownLatch(NUM_THREAD);
ConsumerThread buffer = new ConsumerThread(latch);
for (int i = 0; i < NUM_THREAD; i++){
consumers.add(buffer);
executor.execute(buffer);
latch.countDown();
buffer = new ConsumerThread(latch);
}
for (int i = 0; i < 100; i++){
System.out.println("Status for Thread 0: " + getStatusId(0));
System.out.println("Status for Thread 14: " + getStatusId(14));
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static int getStatusId(int index){
return consumers.get(index).getStatus();
}
}
샘플 출력 :
Status for Thread 0: 5
Status for Thread 14: 0
Status for Thread 0: 7
Status for Thread 14: 2
Status for Thread 0: 7
Status for Thread 14: 4
Status for Thread 0: 6
Status for Thread 14: 3
당신은 당신의 클라이언트 비동기를하고 실제 문제를 해결할 수 있습니다. 그러나 양방향 서비스 (예 : 요청이 대기 중이고 응답이 매우 오랜 시간이 걸리는 경우)를 원하면 클라이언트에 알림 서비스를 게시하여 서버 작업 결과를 수신하고 상호 연관시키는 방법을 구현하십시오 이전에 보낸 요청에 대한 응답 알림 이 시나리오에서는 양 끝이 기술적으로 클라이언트와 서버이지만 클라이언트를 개시 자로 계속 호출합니다. – acelent
내 문제에 관심을 가져 주셔서 감사합니다. 네가 나에게 제안하는 두 가지 해결책의 관점에서, 나는 첫 번째 해결책을 구현했다. 두 번째는 프로젝트의 또 다른 반복의 대상이 반복은 연구 및 개발을 구성합니다 – FiokoSoft