Java多執行緒(五)-執行緒同步(同步方法)
阿新 • • 發佈:2021-10-02
六.執行緒同步(併發)
1.synchronized方法
控制對物件的訪問,每個物件都有一把鎖,每個synchronized方法都必須獲得呼叫該方法的鎖才能執行,方法一旦執行,就獨享該鎖,使用完該物件後釋放鎖,其他執行緒才能獲得鎖,繼續執行。
public synchronized void method(){}
2.synchronized塊
synchronized (obj){}
obj可以是任何物件,稱為同步監視器,推薦使用共享資源作為同步監視器,synchronized方法無需指定同步監視器,因為其就是this。
執行過程:1.第一個執行緒訪問,鎖定同步監視器,執行內容 2.第二個執行緒訪問,同步監視器被鎖,無法訪問,等待第一個執行緒解鎖同步監視器然後訪問。
點選檢視案例
public class Unsafe2 { public static void main(String[] args) { Account account = new Account(200,"home"); // 建立家庭賬戶一共有200w GetMoney boy = new GetMoney(account,200,"boy"); GetMoney girl = new GetMoney(account,50,"girl"); boy.start(); girl.start(); } } class Account{ int money; String id; public Account(int money, String id) { this.money = money; this.id = id; } } class GetMoney extends Thread{ Account account; int get; // 取了多少 int now; // 現餘多少 public GetMoney(Account account, int get,String name) { super(name); this.account = account; this.get = get; } @Override public void run() { synchronized (account){ if (account.money - get < 0){ System.out.println(Thread.currentThread().getName()+":money is not enough"); return; } try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } account.money = account.money - get; now = now + get; System.out.println(account.id+"-account-money:"+account.money); System.out.println(Thread.currentThread().getName()+"-now:"+now); } } }
執行結果
home-account-money:0
boy-now:200
girl:money is not enough