我正在尝试了解 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());
}
}
}
}
在这里,我试图使value
线程安全,一次只能由一个线程访问。当我运行这个程序时,我看到有不止一个线程在运行,value
即使我将它包装在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]
不同的线程正在访问和更改 this value
。有人可以向我解释为什么会这样吗?以及如何使这个全局变量线程安全?