计数器变量不准确地反映了increment方法被调用的次数。为什么会这样,如何修复?(您不必编写代码,只需使用英语。)
import java.util.*;
import java.lang.*;
import java.io.*;
class Foopadoop
{
public static int counter = 0;
public static void main(String[] args) throws Exception {
Runnable r = new Runnable() {
public void run() {
while(true){
counter++;
}
}
};
Thread t1 = new Thread(r);
Thread t2 = new Thread(r);
t1.start();
t2.start();
}
}
我添加了一个信号量,但我不确定是否做对了,或者我该使用锁。
import java.util.*;
import java.lang.*;
import java.io.*;
import java.util.concurrent.Semaphore;
class Foopadoop
{
public static int counter = 0;
Semaphore lock = new Semaphore(0);
public static void main(String[] args) throws Exception {
Runnable r = new Runnable() {
try{public void run() {
while(true){
counter++;
lock.acquire();
}
}
}finally{
lock.release();
}
};
Thread t1 = new Thread(r);
Thread t2 = new Thread(r);
t1.start();
t2.start();
}
}
counter
只在类加载时初始化一次。问题在于,在线程之间更新counter
的可见性不能保证;此外,其值也不能保证原子递增。 - Andy Turner