added ex S2

This commit is contained in:
Louis Heredero 2025-01-07 13:01:22 +01:00
parent dbd83223fe
commit 9be4e8a359
Signed by: HEL
GPG Key ID: 8D83DE470F8544E7

View File

@ -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));
}
}