Konstantin Konstantin - 7 months ago 31
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++) {
System.out.println(j); // 10000000

class parallelCounterDemo {
public static void main(String[] args) {
Thread t1 = new Thread(new Runnable() {
public void run() {
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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download