Answer the question and write a bonus simple example about an atomic variable

This commit is contained in:
Matin
2026-06-14 05:06:32 +04:30
parent 52d5665fc0
commit 85950c58c4
2 changed files with 32 additions and 0 deletions
View File
@@ -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());
}
}