syncronized如何上鎖

2022-01-29 19:17:58 字數 1218 閱讀 3891

上鎖,根據作業系統所說的原則,對共享變數上鎖,對臨界區上鎖。誰訪問臨界資源?就給誰上鎖

同步監視器,它上鎖的物件。

1.用關鍵字給方法上鎖

2.用synchronized**塊上鎖

預設上鎖物件:this,指向自身。就是呼叫這個方法的物件,給他上鎖。

public class synchronizetest 

}class buyticker implements runnable catch (interruptedexception e)

}}//對買票上鎖,鎖的this,this是指當前的物件。

public synchronized void buy() throws interruptedexception

thread.sleep(100);

system.out.println(thread.currentthread().getname()+"拿到"+ticketnum--);

}}

如果給乙個類的方法上鎖了,實際上是給this也就是呼叫方法的這個物件上鎖,比如你要是給run()上鎖,就相當於你去取錢把銀行鎖了。但是取錢的人都還在銀行裡面。所以是要對賬戶上鎖,因為我們逍遙操控的變數就是賬戶。

public class unsafebake 

}class account

}class draw extends thread

@override

public void run()

try catch (interruptedexception e)

account.money = account.money - drawmoney;

nomoney = nomoney +drawmoney;

system.out.println(account.name+"餘額為:"+account.money);

system.out.println(this.getname()+"手裡的錢"+nomoney);//繼承thread可以直接寫this}}

}

public class unsafelist 

}).start();

}try catch (interruptedexception e)

system.out.println(list.size());

}}

python多執行緒上鎖

一般談到多執行緒就會涉及到上鎖的問題,為什麼要上鎖?是為了執行緒安全.比方說我有兩個執行緒,都要拿到乙個唯一的資料 只能被拿一次 如果不上鎖,那麼就很有可能兩個執行緒同時拿,資料就被拿了兩次.如果我們上鎖,我們就限制了拿的操作在某個時間只能有乙個執行緒做,如果這個時候其他執行緒也想做就得等待.這樣就...

linux IPC 記錄上鎖

本節講述的是利用fcntl函式來實現不同程序間的上鎖,不管這些程序有沒有親緣關係。前面講述過有名訊號量同樣也是可以用在沒有親緣關係的程序間上鎖的。而針對執行緒上鎖的一些機制,想要用在不同程序間上鎖,就需要把鎖放在程序共享記憶體區操作。記錄上鎖主要是用到fcntl 函式。include include...

鎖 記錄上鎖

記錄鎖的功能是 當乙個程序正在讀或者修改檔案的某乙個部分時,它可以阻止其他程序修改同一檔案區。記錄鎖其實是 位元組範圍鎖,因為它鎖定的只是檔案中的乙個區域,也可能是整個檔案。1.基礎介紹 svr3通過fcntl函式增加了記錄鎖功能。fcntl函式的原型已經在以前給出,這邊再重複一次。include ...