Skip to content

Instantly share code, notes, and snippets.

@ludat
Created October 21, 2015 18:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ludat/1d563d41147dac88de36 to your computer and use it in GitHub Desktop.
Save ludat/1d563d41147dac88de36 to your computer and use it in GitHub Desktop.
Concurrency exmple with N consumers
package com.company;
import java.util.ArrayList;
import java.util.List;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicInteger;
public class Main {
public static void main(String[] args) throws InterruptedException {
// write your code here
Queue<Integer> numbersQueue = new ConcurrentLinkedQueue<>();
List<NumbersThread> threads = new ArrayList<>();
AtomicInteger consumed = new AtomicInteger();
consumed.set(0);
for (int i = 0; i < 5; i++) {
threads.add(new NumbersThread(numbersQueue, consumed));
}
for (NumbersThread thread : threads) {
thread.start();
}
for (int i = 0; i < 1000; i++) {
numbersQueue.offer(i);
}
}
}
public class NumbersThread extends Thread {
private AtomicInteger consumed;
private boolean stopped = false;
private Queue<Integer> queue;
private static Integer MAX_CONSUMED = 1000;
NumbersThread (Queue newQueue, AtomicInteger globalConsumed) {
queue = newQueue;
consumed = globalConsumed;
}
public void run () {
while (!stopped && consumed.get() < MAX_CONSUMED) {
Integer newValue = queue.poll();
if (null != newValue) {
consumed.getAndAdd(1);
System.out.println("Processed " + newValue);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment