Skip to content

codes #170

@siddharthrgade21-a11y

Description

@siddharthrgade21-a11y

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

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions