Skip to content

codes #171

@siddharthrgade21-a11y

Description

@siddharthrgade21-a11y

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

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