-
Notifications
You must be signed in to change notification settings - Fork 694
Open
Description
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class SynchronizedCounterDemo {
private int count = 0;
// The synchronized keyword ensures only one thread can execute this method at a time
public synchronized void increment() {
count++;
}
public int getCount() {
return count;
}
public static void main(String[] args) throws InterruptedException {
SynchronizedCounterDemo counter = new SynchronizedCounterDemo();
int numberOfThreads = 1000;
ExecutorService executorService = Executors.newFixedThreadPool(10);
for (int i = 0; i < numberOfThreads; i++) {
executorService.submit(() -> counter.increment());
}
executorService.shutdown();
// Wait until all threads are finished
executorService.awaitTermination(1, TimeUnit.MINUTES);
// The expected count is 1000. Without 'synchronized', it would likely be less due to race conditions.
System.out.println("Final count: " + counter.getCount());
}
}
Metadata
Metadata
Assignees
Labels
No labels