My problem is that the code should increment a
1000 times and then output it. But sometimes a
isn't 1000 at the end.
public class Counter extends Thread {
private static Integer a = 0;
public void run() {
for (int i = 0; i < 100; i++) {
a++;
}
}
public static void main(String[] args) {
Counter[] ca = new Counter[10];
for (int i = 0; i < 10; i++) {
ca[i] = new Counter();
ca[i].start();
}
for (Counter c : ca) {
try {
c.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(a);
}
This code is the original code that is obviously not going to work because I have multiple Threads accessing the variable a. I've tried putting a synchronized(this)
around a++;
and marking a
as volatile
but I still sometimes get a false Result. The only way I've found to make it work reliably it to put join()
into the for
loop, but that kind of defeats the point of using Threads in the first place.
Any help is appreciated.