Answer the question and write a bonus simple example about an atomic variable
This commit is contained in:
@@ -0,0 +1,32 @@
|
|||||||
|
package dev.banking.model;
|
||||||
|
import java.util.concurrent.atomic.AtomicInteger ;
|
||||||
|
public class bonus {
|
||||||
|
private static int normalVariable = 0 ;
|
||||||
|
private static final AtomicInteger atomicVariable = new AtomicInteger(0) ;
|
||||||
|
public static void main(String[] args) throws InterruptedException{
|
||||||
|
int numberOfThrad = 10 ;
|
||||||
|
int incrementsPerThread = 10000 ;
|
||||||
|
Thread[] threads = new Thread[numberOfThrad] ;
|
||||||
|
Runnable task = () -> {
|
||||||
|
for (int i = 0 ; i < incrementsPerThread ; i ++ )
|
||||||
|
{
|
||||||
|
normalVariable ++ ;
|
||||||
|
atomicVariable.incrementAndGet() ;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
for (int i = 0 ; i < numberOfThrad ; i ++)
|
||||||
|
{
|
||||||
|
threads[i] = new Thread(task) ;
|
||||||
|
threads[i].start();
|
||||||
|
}
|
||||||
|
for (Thread thread : threads)
|
||||||
|
{
|
||||||
|
thread.join();
|
||||||
|
}
|
||||||
|
System.out.println("Expected Value (مقدار مورد انتظار): " + (numberOfThrad * incrementsPerThread));
|
||||||
|
System.out.println("Normal Integer Result (متغیر معمولی): " + normalVariable);
|
||||||
|
System.out.println("Atomic Integer Result (متغیر اتمیک): " + atomicVariable.get());
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user