July 2017
Intermediate to advanced
284 pages
6h 45m
English
Next, we create a thread pool with five threads in it using Java’s ExecutorService, and we submit 10,000 tasks to the service. Each task increments both our normal counter and our atomic counter. The full code snippet follows.
| | public class ConcurrencyExamples { |
| | |
| | private static int counter = 0; |
| | private static AtomicInteger atomicCounter = |
| | new AtomicInteger(0); |
| | |
| | public static void main(String[] args) |
| | throws InterruptedException { |
| | ExecutorService executors = Executors.newFixedThreadPool(5); |
| | for (int i = 0; i < 10000; i++) { |
| | executors.execute(new Runnable() { |
| | public void run() { |
| | counter++; |
| | atomicCounter.incrementAndGet(); |
| | } |
| | }); |
| | } |
| | |
| | // Shut ... |
Read now
Unlock full access