您應該監聽來自客戶端的調用(在服務器端點之一上)輪詢狀態,並讓消費者線程實現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();
}
}
}
然後嘗試一個簡單的main方法(我實現了一個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