adspace


How to update value using threads. Write code?

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


Please Help Members By Posting Answers For Below Questions

can any one know about NIC (National Informatics Centre) questions Patterns and full detail about written exam, and interview send to softshikha2005@yahoo.com.in Thank you

2160