Skip to content

Codes #176

@siddharthrgade21-a11y

Description

@siddharthrgade21-a11y

public class SynchronizedCounter {
private int count = 0;

// The synchronized keyword ensures that only one thread can execute this method at a time
public synchronized void increment() {
    count++;
}

public synchronized int getCount() {
    return count;
}

}

public class CounterTest {
public static void main(String[] args) throws InterruptedException {
SynchronizedCounter counter = new SynchronizedCounter();

    // Create two threads that increment the counter 1000 times each
    Thread t1 = new Thread(() -> {
        for (int i = 0; i < 1000; i++) {
            counter.increment();
        }
    });

    Thread t2 = new Thread(() -> {
        for (int i = 0; i < 1000; i++) {
            counter.increment();
        }
    });

    t1.start();
    t2.start();

    // Wait for both threads to complete
    t1.join();
    t2.join();

    System.out.println("Final count: " + counter.getCount()); // Should be 2000
}

}

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