我希望两个线程共享该变量,但有时在运行时它会打印两次两次,而不是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,然后出现了这个问题。
您没有在System.out.println
调用中同步访问,因此“第二”线程有时会在“第一个线程”打印之前递增。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句