【发布时间】:2015-07-08 22:10:23
【问题描述】:
我一直在研究java中的同步,并尝试运行以下程序
public class Example {
public static void main(String[] args) {
Counter counterA = new Counter();
Counter counterB = new Counter();
Thread threadA = new CounterThread(counterA);
Thread threadB = new CounterThread(counterB);
threadA.start();
threadB.start();
}
}
class CounterThread extends Thread {
protected Counter counter = null;
public CounterThread(Counter counter){
this.counter = counter;
}
public void run() {
for(int i=0; i<2; i++){
counter.add(i);
}
}
}
class Counter {
long count = 0;
public synchronized void add(long value){
this.count += value;
System.out.println(this.count);
}
}
当我运行上述代码时,当我将 Example 类作为 java 应用程序运行或调试 Example 类时,它会给出相同的输出
0
1
0
1
但是,如果我将计数器类的计数变量的访问修饰符修改为静态,如下所述:
static long count = 0;
现在如果尝试运行示例类,我得到的输出为
0
1
0
2
但是当我调试示例类时,我得到的输出为
0
1
1
2
谁能帮我理解其中的区别。 在此先感谢并道歉,因为我是多线程概念的新手
【问题讨论】:
标签: java multithreading static