< /code>
Я запустил два потока: < /p>
- Thread 1: увеличение thread1count
- Thread 2: Incurments Thread2count
Оба потока также увеличивают общую переменную GlobalTotalCount .
Я ожидаю:
thread1Count + thread2Count == globalTotalCount
< /code>
Тем не менее, на практике
сумма двух счетчиков потока делает не < /strong> совпадает с окончательным значением GlobalTotalCount. (Большую часть времени) < /p>
Вот мой код: < /p>
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
/**
* Demonstrates a race condition between two threads incrementing shared counters.
* The sum of thread-specific counts and the global total will often differ due to missing synchronization.
*/
public class RaceConditionDemo {
// Shared counters (not thread-safe)
private static int globalTotalCount = 0;
private static int thread1Count = 0;
private static int thread2Count = 0;
// Flag to signal threads to stop; volatile ensures visibility between threads
private volatile boolean shouldRun = true;
public RaceConditionDemo() {
// Create and use a thread pool for our worker threads
try (ExecutorService executor = Executors.newCachedThreadPool()) {
executor.execute(thread1Task);
executor.execute(thread2Task);
// Let threads run for 1 seconds
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
// Stop threads
shouldRun = false;
// Shutdown thread pool and wait for tasks to finish
executor.shutdown();
try {
if (!executor.awaitTermination(2, TimeUnit.SECONDS)) {
executor.shutdownNow();
}
} catch (InterruptedException e) {
executor.shutdownNow();
Thread.currentThread().interrupt();
}
}
// Print results
System.out.println("Result:");
System.out.println("\tThread 1 Count:\t" + thread1Count);
System.out.println("\tThread 2 Count:\t" + thread2Count);
System.out.println("--------------------------------");
System.out.println("\tSum of thread counts:\t" + (thread1Count + thread2Count));
System.out.println("\tGlobal total count:\t\t" + globalTotalCount);
System.out.println("--------------------------------");
int difference = thread1Count + thread2Count - globalTotalCount;
if (difference != 0) {
System.out.println("Difference:\t" + difference + " => Race condition detected!");
} else {
System.out.println("Difference:\t" + difference + " => No race condition detected! (this time)");
}
}
// Worker for thread 1: increments its own and the global counter, prints its progress
private final Runnable thread1Task = () -> {
while (shouldRun) {
globalTotalCount++;
thread1Count++;
System.out.println("[Thread 1]\tCall:\t" + thread1Count + "\n");
try {
Thread.sleep(1);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
};
// Worker for thread 2: increments its own and the global counter, prints its progress
private final Runnable thread2Task = () -> {
while (shouldRun) {
globalTotalCount++;
thread2Count++;
System.out.println("[Thread 2]\tCall:\t" + thread2Count + "\n");
try {
Thread.sleep(1);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
};
public static void main(String[] args) {
new RaceConditionDemo();
}
}
Подробнее здесь: https://stackoverflow.com/questions/251 ... not-atomic