Skip to content

Codes #263

@siddharthrgade21-a11y

Description

@siddharthrgade21-a11y

class Counter {
private int count = 0;
// Synchronized method to ensure thread safety
public synchronized void increment() {
count++;
}
public int getCount() {
return count;
}
}

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

    // Define a task for multiple threads
    Runnable task = () -> {
        for (int i = 0; i < 1000; i++) counter.increment();
    };

    Thread t1 = new Thread(task);
    Thread t2 = new Thread(task);

    t1.start(); t2.start();
    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