How to update value using threads. Write code?



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

Post New Answer

More Windows Threads Interview Questions

What is windows daemon?

1 Answers  


WHAT IS A DAEMON?

5 Answers   IBM,


what are the different types of codes in thread in windows os?

1 Answers   HP, IBM, Reliance,


how do u share printer through FTP(fire transfer protocol)?

1 Answers  


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?

1 Answers  


Explain the difference between ntfs4 and ntfs5?

1 Answers  


What are types of threads?

1 Answers  


What is the difference between a computer process and thread?

1 Answers  


How to Kill a Particular Process in windows?

5 Answers   Tomax,


What is thread safety and synchronization?

1 Answers  


What are the different identifier states of a thread?

1 Answers  


Where is taskkill located?

1 Answers  


Categories