我有一个共享变量计数,我在方法中递增它increment(),并且两个线程正在访问它。我得到了错误的最终计数。这是代码片段:
public class ReentrantLockTest {
static volatile int count = 0;
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
for(int i = 0; i < 10000; i++){
increment();
}
}
});
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
for(int i = 0; i < 10000; i++){
increment();
}
}
});
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println("Counter variable : "+count);
}
private static …Run Code Online (Sandbox Code Playgroud)