Konstantin Konstantin - 4 months ago 15
Java Question

Can a separate thread change static variable?

After surfing the web, I am still confused about the following thread behavior. I am aware that static variables are shared within the same classloader, however there's sth definitely missing in this extract:

public class parallelCounter {
public static final int N = 100000000;
public static int j = 0;
public static void inc() {
for (int i = 0; i < N; i++) {
j++;
}
System.out.println(j); // 10000000
}
}

class parallelCounterDemo {
public static void main(String[] args) {
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
parallelCounter.inc();
}
});
t1.start();
System.out.println(parallelCounter.j); // 0 Why?
}
}

Answer Source

t1 is a new Thread which start asynchronous and your code continue without calling inc() function so j number is still 0