Answer the question
In order to leave comments, you need to log in
How to correctly change a shared variable from two threads?
Good evening!
There is a task like this:
"Write a short program in which two threads both increment a shared integer repeatedly, without proper synchronization, 1000 times, printing the result at the end of the program. Modify the program to use synchronized to ensure that increments on the shared variables are atomic." - Write a short program in which two threads simultaneously increment a shared variable, without synchronization, 1000 times, printing the result at the end of the program. Add synchronization to the program to ensure that the increments of the shared variable are atomic.
Wrote the following code:
public class Main {
private static int element = 0;
private static Object lock = new Object();
public static void main(String[] args) {
new Thread() {
public void run() {
synchronized (lock) {
for (int i = 0; i < 1000; i++)
element++;
}
}
}.start();
new Thread() {
public void run() {
synchronized (lock) {
for (int i = 0; i < 1000; i++)
element++;
}
}
}.start();
System.out.println(element);
}
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question