【发布时间】:2019-07-16 04:23:33
【问题描述】:
我读到 volatile 变量副本将由所有线程共享,一旦执行完成,更新值将由每个线程获取,但是在下面使用线程池的程序中没有给出我期望的输出,任何一个都可以告诉我原因?
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
class Task implements Runnable{
volatile int v1=10;
private String name;
public Task(String name) {
this.name=name;
}
public synchronized void run() {
v1=v1+10;
System.out.println(name +"is entered "+v1);
}
}
public class ThreadPoolTest {
public static void main(String[] args) {
Runnable r1 = new Task("Thread 1");
Runnable r2 = new Task("Thread 2");
Runnable r3 = new Task("Thread 3");
ExecutorService executor = Executors.newFixedThreadPool(5);
executor.execute(r1);
executor.execute(r2);
executor.execute(r3);
executor.shutdown();
}
}
outPut:
Thread 1is entered 20
Thread 2is entered 20
Thread 3is entered 20
but if we change from volatile to static its giving below output:
Thread 1is entered 20
Thread 3is entered 30
Thread 2is entered 40
【问题讨论】:
-
这完全有意义,因为您创建了 Task 类的 3 个实例,并且它的实例有自己的 v1 变量。因此,当您将 ot 设为静态时,所有任务都共享同一个变量。这就是为什么它会变成 20 30 40。
-
不要
change from volatile to static,而是在保留易失性的同时添加静态(即从“易失性”更改为“静态易失性”)
标签: java multithreading static threadpool thread-synchronization