我看不出最终的计数器值为20000.这段代码有什么问题?方法同步线程问题
public class Synchronize2 {
public static void main(String[] args) {
Threading t1 = new Threading();
Threading t2 = new Threading();
t1.start();
t2.start();
try {
t1.join();
t2.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Threading.counter);
}
}
class Threading extends Thread {
static int counter;
public synchronized void incrementer() {
counter++;
}
public void run() {
for (int i=0; i<10000; i++) {
incrementer();
}
}
}
您正在同步两个不同的对象。 – SLaks
@SLaks。增量值字段是静态的 –
@MarkusMalkusch:正确。他的代码不是线程安全的。 – SLaks