所以我正在测试synchronized
关键词。这是我尝试过的一个例子:
public class MyTest {
static int i = 0;
public static void main(String[] args) {
new Thread(t1).start();
new Thread(t2).start();
}
private static void countMe(String name){
i++;
System.out.println("Current Counter is: " + i + ", updated by: " + name);
}
private static Runnable t1 = new Runnable() {
public void run() {
try{
for(int i=0; i<5; i++){
countMe("t1");
}
} catch (Exception e){}
}
};
private static Runnable t2 = new Runnable() {
public void run() {
try{
for(int i=0; i<5; i++){
countMe("t2");
}
} catch (Exception e){}
}
};
}
当我运行它时,调用的输出countMe()
两个线程的方法生成以下输出:
Current Counter is: 1
Current Counter is: 2
Current Counter is: 4
Current Counter is: 5
Current Counter is: 6
Current Counter is: 7
Current Counter is: 3
Current Counter is: 8
Current Counter is: 9
Current Counter is: 10
当我改变方法时countMe()
to:
private synchronized static void countMe(){
i++;
System.out.println("Current Counter is: " + i);
}
我得到这个输出:
Current Counter is: 1
Current Counter is: 2
Current Counter is: 3
Current Counter is: 4
Current Counter is: 5
Current Counter is: 6
Current Counter is: 7
Current Counter is: 8
Current Counter is: 9
Current Counter is: 10
虽然这让我清楚地了解了synchronized
,我想知道是否还有其他原因,我们可以使用synchronized
。或者我在这里所做的,是我们需要使用这个的唯一原因synchronized
关键词?
谢谢。
EDIT:另一件令我困惑的事情是,在第一个输出中,为什么计数器在 7 之后变为 3。这对我来说似乎有点不可能,但每次我尝试时都会出现类似的结果,这是正常的吗?