added ex S2
This commit is contained in:
		
							
								
								
									
										42
									
								
								src/exercises/ex_s2/TestingAtomicInteger.java
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										42
									
								
								src/exercises/ex_s2/TestingAtomicInteger.java
									
									
									
									
									
										Normal 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)); | ||||||
|  |     } | ||||||
|  | } | ||||||
		Reference in New Issue
	
	Block a user