Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.concurrent.*;
- class WorkQueue{
- public static void main (String[] args){
- int capacity = n;
- ExecutorService executor = new ExecutorService (new FixedThreadPool(n)); //CachedThreadPool is another alternative with the caveat that when all threads are busy, new threads are spawned
- BlockingQueue queue = new ArrayBlockingQueue (100);// Some analysis will have to be done to understand how many messages will be placed in the
- //queue by the producers. For now it's an arbitrary 100.
- for int(i = 0; i < numOfProducers; i++){
- executor.submit(new Producer(queue, "Hello"));
- }
- Future result = executor.submit(new Consumer(queue));//consumer reads from the queue
- class Producer implements Runnable{
- private final BlockingQueue queue;
- private String message;
- //constructur
- Public Producer(BlockingQueue queue, String message){
- this.queue = queue;
- this.message = message;
- }
- @override
- public void run(){//add try catch block as necessary
- queue.put(message);
- }
- }
- Class Consumer implements Callable{// Because I'll get a future based on this
- private final BlockingQueue queue;
- public Consumer(BlockingQueue queue){
- this.queue = queue;
- }
- @override
- public String call (){
- String message = queue.take();
- return "Success";
- }
- }
- }
Add Comment
Please, Sign In to add comment