Skip to content

Instantly share code, notes, and snippets.

@nfisher
Created September 5, 2016 16:05
Show Gist options
  • Save nfisher/f90eec6cf7b626fdcffbbfae87ab9540 to your computer and use it in GitHub Desktop.
Save nfisher/f90eec6cf7b626fdcffbbfae87ab9540 to your computer and use it in GitHub Desktop.
Worker and Co-ordinator threads.
import java.lang.*;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
class Signal {
ReadWriteLock lock = new ReentrantReadWriteLock();
volatile boolean running = true;
public void stop() {
lock.writeLock().lock();
running = false;
lock.writeLock().unlock();
}
public boolean isStopped() {
boolean running;
lock.readLock().lock();
running = this.running;
lock.readLock().unlock();
return !running;
}
}
class QueueMonitor implements Runnable {
final String queue;
final Signal signal;
public QueueMonitor(final String queue, final Signal signal) {
this.queue = queue;
this.signal = signal;
}
public void run() {
try {
for (; ; ) {
// do some work...
Thread.sleep(1000);
System.out.println(queue);
if (signal.isStopped()) break;
}
} catch(InterruptedException ex) {
ex.printStackTrace();
}
}
}
class Coordinator implements Runnable {
final Signal signal;
public Coordinator(final Signal signal) {
this.signal = signal;
}
public void run() {
System.console().readLine();
signal.stop();
}
}
public class Main {
public static void main(final String[] args) throws InterruptedException {
final String[] queues = {"policies", "settlements", "claims", "quotes"};
final Thread[] threads = new Thread[queues.length];
final Signal signal = new Signal();
for (int i = 0; i < queues.length; i++) {
System.out.println(queues[i]);
threads[i] = new Thread(new QueueMonitor(queues[i], signal));
threads[i].start();
}
Thread t = new Thread(new Coordinator(signal));
t.start();
for (int j = 0; j < queues.length; j++) {
threads[j].join();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment