我希望你能帮我翻译一下与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
线程安全,只能被一个线程访问。当我运行此程序时,即使我将其包装在synchronized
块中,仍会有多个线程操作value
。当然,这个循环将是无限的,但这只是一个例子,我在几秒钟后手动停止了这个程序,所以我有:
2470
Thread[pool-1-thread-3,5,main]
2470
Thread[pool-1-thread-5,5,main]
2470
Thread[pool-1-thread-2,5,main]
不同的线程正在访问和更改这个value
。有人能解释一下为什么会这样吗?如何使这个全局变量线程安全?
MyThread
类不应该继承Thread
,而应该实现Runnable
接口。 - Gray