對(duì)于字符串医舆,當(dāng)且僅當(dāng)s.equals(t)為真炕柔,但s==t未必真脑蠕,
當(dāng)我們定義一個(gè)函數(shù)购撼,希望equals相等的用戶名不能同時(shí)執(zhí)行,
public static void test(String a,String lock){
/**
* 當(dāng)且僅當(dāng)s.equals(t)為真谴仙,但s==t未必真
*/
synchronized(lock){
while (true){
System.out.println(a);
}
}
}
上面方面假如同時(shí)調(diào)用
test("qqqqqqqq",new String("111")) ;
test("kkkkkkkkk",new String("111")) ;
由于new String("111")==new String("111") 迂求;為false ,并不能達(dá)到互鎖晃跺,因?yàn)槔锩娴膌ock對(duì)象不相等揩局,不是同一把鎖
如何實(shí)現(xiàn)互鎖呢?使用intern方法掀虎,可以實(shí)現(xiàn)
public static void test(String a,String lock){
/**
* lock.intern() : 當(dāng)且僅當(dāng)s.equals(t)為真凌盯,則s.intern()==t.intern()為真
* 當(dāng)且僅當(dāng)s.equals(t)為真,但s==t未必真
*/
synchronized(lock.intern()){
while (true){
System.out.println(a);
}
}
}
String對(duì)象的intern方法的官方解釋:
It follows that for any two strings s and t, s.intern() == t.intern() is true if and only if s.equals(t) is true.
翻譯為:當(dāng)且僅當(dāng)s.equals(t)為真烹玉,則s.intern()==t.intern()為真