From 9be4e8a359916dae08c14317f4641723cb42174d Mon Sep 17 00:00:00 2001 From: LordBaryhobal Date: Tue, 7 Jan 2025 13:01:22 +0100 Subject: [PATCH] added ex S2 --- src/exercises/ex_s2/TestingAtomicInteger.java | 42 +++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 src/exercises/ex_s2/TestingAtomicInteger.java diff --git a/src/exercises/ex_s2/TestingAtomicInteger.java b/src/exercises/ex_s2/TestingAtomicInteger.java new file mode 100644 index 0000000..ec19315 --- /dev/null +++ b/src/exercises/ex_s2/TestingAtomicInteger.java @@ -0,0 +1,42 @@ +package exercises.ex_s2; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.concurrent.atomic.AtomicIntegerArray; + +public class TestingAtomicInteger { + public static void main(String[] args) throws InterruptedException { + int[] nonAtomic = new int[5]; + AtomicIntegerArray atomic = new AtomicIntegerArray(5); + + for (int i = 0; i < 5; i++) { + nonAtomic[i] = i; + atomic.set(i, i); + } + + System.out.println("Starting values atomic array: " + atomic); + System.out.println("Starting values of non atomic array: " + Arrays.toString(nonAtomic)); + System.out.println("Creating 3 threads to increment the values within those two arrays"); + + Thread[] threads = new Thread[3]; + for (int i = 0; i < 3; i++) { + threads[i] = new Thread(() -> { + for (int j = 0; j < 100000; j++) { + for (int k = 0; k < 5; k++) { + nonAtomic[k] += 1; + atomic.incrementAndGet(k); + } + } + }); + threads[i].start(); + } + + for (int i = 0; i < 3; i++) { + threads[i].join(); + } + + System.out.println("Final values atomic array: " + atomic); + System.out.println("Final values of non atomic array: " + Arrays.toString(nonAtomic)); + } +}