需要在实现的java代码中的易失性和非易失性概念方面的帮助吗?
我编写了以下代码来理解java中的volatile概念,但输出似乎令人困惑,而不是澄清这个概念。欢迎并感谢更正、澄清和反馈需要在实现的java代码中的易失性和非易失性概念方面的帮助吗?,java,multithreading,volatile,Java,Multithreading,Volatile,我编写了以下代码来理解java中的volatile概念,但输出似乎令人困惑,而不是澄清这个概念。欢迎并感谢更正、澄清和反馈 package threading; public class UnSyncRead { //volatile static int value = 987; static int value = 987; public static void main(String[] args) { ThreadEx4 t = new Th
package threading;
public class UnSyncRead {
//volatile static int value = 987;
static int value = 987;
public static void main(String[] args) {
ThreadEx4 t = new ThreadEx4(value);
t.start();
for(int i=0;i<4;i++) {
Thread thread = new Thread( new ThreadEx3(value));
thread.start();
}
}
}
class ThreadEx3 implements Runnable{
private int i;
public ThreadEx3(int i) {
this.i=i;
}
@Override
public void run() {
System.out.println(Thread.currentThread().getId()+ " "+Thread.currentThread().getName()+" "+ " inside "+i);
}
}
class ThreadEx4 extends Thread{
private int i;
public ThreadEx4(int i) {
this.i=i;
}
public void run() {
++i;
System.out.println("changed the value to "+i);
}
}
但是如果我修改代码使value
variablevolatile
,方法是执行以下更改并运行代码
public class UnSyncRead {
volatile static int value = 987;
//static int value = 987;
public static void main(String[] args) {
ThreadEx4 t = new ThreadEx4(value);
t.start();
for(int i=0;i<4;i++) {
Thread thread = new Thread( new ThreadEx3(value));
thread.start();
}
}
}
我的问题是为什么for循环中的线程仍然将value
变量的值读取为987
,而不是988
,即使在实现volatile关键字之后也是如此
changed the value to 988
12 Thread-1 inside 987
13 Thread-2 inside 987
14 Thread-3 inside 987
15 Thread-4 inside 987
我将非常感谢您对这个问题的回答 这与多线程无关,这是一个更基本的问题
class ThreadEx4 extends Thread{
private int i;
public ThreadEx4(int i) {
this.i=i;
}
public void run() {
++i;
System.out.println("changed the value to "+i);
}
}
您在此处更改的是私有变量i
,而不是全局静态
字段
Java通过值传递信息。因此,当您说newthreadex4(myInteger)
时,构造函数将收到myInteger
中的数字。它对本地副本所做的任何操作都不会影响myInteger
要继续多线程实验,请去掉局部变量并执行以下操作
class Ex4 extends Runnable {
@Override
public void run(){
int newValue = ++UnSyncRead.value;
System.out.println("changed the value to "+newValue);
}
}
// and the same for the other runnables
class Ex4 extends Runnable {
@Override
public void run(){
int newValue = ++UnSyncRead.value;
System.out.println("changed the value to "+newValue);
}
}
// and the same for the other runnables