Created
October 21, 2015 18:28
-
-
Save ludat/1d563d41147dac88de36 to your computer and use it in GitHub Desktop.
Concurrency exmple with N consumers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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