我希望两个线程共享变量,但有时在运行时它会打印两次,而不是 1 和 2。
public class man implements Runnable{
int value = 0;
public static void main(String[] args){
Runnable job = new man();
Thread work1 = new Thread(job);
work1.setName("Thread1");
Thread work2 = new Thread(job);
work2.setName("Thread2");
work1.start();
work2.start();
}
public void run(){
synchronized(this){
value = value + 1;
}
System.out.println("VALUE = " + value +", Running " + Thread.currentThread().getName());
}
}
有时输出是:
VALUE = 2, Running Thread2
VALUE = 2, Running Thread1
其他时间是:
VALUE = 1, Running Thread2
VALUE = 2, Running Thread1
为什么会这样?我在 HeadFirst 书中学习 Java,出现了这个问题。