-
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;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class AdvancedConcurrencyDemo {
private int count = 0;
private final Lock lock = new ReentrantLock();
public void increment() {
lock.lock(); // Acquire the lock
try {
// Critical section
count++;
} finally {
lock.unlock(); // Release the lock in a finally block
}
}
public static void main(String[] args) throws InterruptedException {
AdvancedConcurrencyDemo demo = new AdvancedConcurrencyDemo();
ExecutorService executor = Executors.newFixedThreadPool(10);
for (int i = 0; i < 1000; i++) {
executor.submit(demo::increment); // Use method reference for conciseness
}
executor.shutdown();
executor.awaitTermination(1, TimeUnit.MINUTES);
System.out.println("Final count is: " + demo.count); // Expected: 1000
}
}
Metadata
Metadata
Assignees
Labels
No labels