Threads in Java
We need to control access to shared state ( when multiple threads are at work ), to avoid unexpected results. In the case of the program below the shared state is the int sheepCount. 10 different threads call the method incrementAndReport() . Without thread management
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | public class Ch18SheepManager { private int sheepCount = 0; private void incrementAndReport() { Thread t = Thread.currentThread(); System.out.print("sheepcount = " + (++sheepCount) + " Worker - " + t.getName()); } public static void main(String[] args) throws Exception { var service = Executors.newFixedThreadPool(20); var manager = new Ch18SheepManager(); for (int i = 0; i < 10; i++) service.submit(() -> manager.incrementAndReport()); } } |
Output ( wonky ) Every thread is trying to … Read more