You would to listen to calls from the client polling the status (on one of the server's endpoint), and have your consumer threads implement a getStatus
method, while updating the status inside the run method. About the consumer threads, a crude implementation would look like that:
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();
}
}
}
Then trying a simple main method (I implemented a CountDownLatch to have all my threads starting at the same time, it's not mandatory):
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();
}
}
Sample output:
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