public class Count {
private static int counter = 0 ;
public static int getCount(){
// 非線程安全
return counter++;
}
}
- 第一種(不推薦鞋仍,功力不夠,用錯(cuò)會(huì)達(dá)不到同步效果)synchronized正確用法
public class Count {
private static int counter = 0 ;
public static synchronized int getCount(){
// 線程安全,但是synchronized加在方法上會(huì)鎖住整個(gè)Count對(duì)象
return counter++;
}
}
- 第二種
public class Count {
private static int counter = 0 ;
public static int getCount(){
// 線程安全,不會(huì)鎖住整個(gè)Count對(duì)象
synchronized(Count.class){
return counter++;
}
}
}
- 第三種(優(yōu)先選擇)
public class Count {
private static AtomicInteger counter = new AtomicInteger(0);
public static int getCount(){
// 線程安全,以原子方式將當(dāng)前值加1,注意:這里返回的是自增前的值提鸟。
return counter.getAndIncrement();
}
}
參考: