java 全局变量线程安全_Java中的线程安全全局变量

我试图了解

java中的线程安全机制,我需要一些帮助.我上课了:

public class ThreadSafe {

private Executor executor = new ScheduledThreadPoolExecutor(5);

private long value = 0;

public void method() {

synchronized (this) {

System.out.println(Thread.currentThread());

this.value++;

}

}

private synchronized long getValue() {

return this.value;

}

public static void main(String... args) {

ThreadSafe threadSafe = new ThreadSafe();

for (int i = 0; i < 10; i++) {

threadSafe.executor.execute(new MyThread());

}

}

private static class MyThread extends Thread {

private ThreadSafe threadSafe = new ThreadSafe();

private AtomicBoolean shutdownInitialized = new AtomicBoolean(false);

@Override

public void run() {

while (!shutdownInitialized.get()) {

threadSafe.method();

System.out.println(threadSafe.getValue());

}

}

}

}

在这里,我试图使值线程安全,一次只能由一个线程访问.当我运行这个程序时,我发现即使我将它包装在synchronized块中,也有多个线程对该值进行操作.当然这个循环将是无限的,但它只是一个例子,我几秒后手动停止这个程序,所以我有:

2470

Thread[pool-1-thread-3,5,main]

2470

Thread[pool-1-thread-5,5,main]

2470

Thread[pool-1-thread-2,5,main]

不同的线程正在访问并更改此值.有人可以向我解释为什么会这样吗?以及如何使这个全局变量线程安全?

你可能感兴趣的:(java,全局变量线程安全)