adspace
Answer Posted / Upasna
Here's a simple example of updating a shared variable (counter) in Java using threads:
```java
public class Counter {
private int count = 0;
private final Object lock = new Object();
public void increment() {
synchronized(lock) {
count++;
}
}
public int getCount() {
return count;
}
}
// Usage
Counter counter = new Counter();
Thread[] threads = new Thread[10];
for (int i = 0; i < threads.length; ++i) {
threads[i] = new Thread(() -> {
for (int j = 0; j < 1000; ++j) {
counter.increment();
}
});
}
for (Thread thread : threads) {
thread.start();
}
for (Thread thread : threads) {
thread.join();
}
System.out.println(counter.getCount());
```
| Is This Answer Correct ? | 0 Yes | 0 No |
Post New Answer View All Answers