How to update value using threads. Write code?
Answer / 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 |
What is windows daemon?
WHAT IS A DAEMON?
what are the different types of codes in thread in windows os?
how do u share printer through FTP(fire transfer protocol)?
What is the reason for getting the dialogue box (send this error to microsoft giving options as send to microsoft and dont send) when we abort from the any workwhen it was struck?
Explain the difference between ntfs4 and ntfs5?
What are types of threads?
What is the difference between a computer process and thread?
How to Kill a Particular Process in windows?
What is thread safety and synchronization?
What are the different identifier states of a thread?
Where is taskkill located?