-
Notifications
You must be signed in to change notification settings - Fork 694
Open
Description
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
Labels
No labels