java中線程的同步

來源:互聯網
上載者:User

標籤:

線程同步:

當有兩個進程並發修改同一檔案時就可能造成異常。

意思就是當一個線程要改變一個檔案的內容時,卻sleep了一段時間,這時另一個線程卻改變了這個檔案的內容。最後就會出現錯誤的結果。

為瞭解決這個問題,java多線程支援引入了同步監視器來解決這個問題。使用同步監視器的通用方法就是同步代碼塊。

同步代碼塊的文法格式如下:

synchronized(obj){

······

//此處的代碼就是同步代碼塊

上面文法格式中synchronized後括弧裡的obj就是同步監視器,上面代碼的含義是:線程開始執行同步代碼塊之前,必須先獲得對同步監視器的鎖定。

 

注意:

任何時刻智能有一個線程可以獲得對同步監視器的鎖定,當同步代碼塊執行完成後,該線程會釋放對該同步監視器的鎖定。

 

同步監視器:共用資源的對象。

 1 public class SynchronizedClass extends Thread{ 2     private Account account; 3     private double drawbalance; 4     public SynchronizedClass(String name,Account account,double drawbalance){ 5         super(name); 6         this.account=account; 7         this.drawbalance=drawbalance; 8         start(); 9     }10     public void run(){11         synchronized(account){12             if(drawbalance>account.getBalance()){13                 System.out.println("餘額不足!");14             }else{15                 System.out.println("吐錢成功!");16                 try{17                     sleep(100);18                     account.setBalance(account.getBalance()-drawbalance);19                     System.out.println("餘額為:"+account.getBalance());20                 }catch(Exception e){21                     System.out.println(e);22                 }23             }24         }25     }26     public static void main(String[] args){27         Account a=new Account("劉騰",100000);28         new SynchronizedClass("A線程",a,100000);29         new SynchronizedClass("B線程",a,10000);30     }31 }32 //賬戶33 class Account {34     private String name;35     private double balance;36     public Account(){}37     public Account(String name,double balance){38         this.name=name;39         this.balance=balance;40     }41     public void setName(String name){42         this.name=name;43     }44     public void setBalance(double balance){45         this.balance=balance;46     }47     public String getName(){48         return name;49     }50     public double getBalance(){51         return balance;52     }53     public boolean equals(Object obj){54         if(this==obj)return true;55         if(obj!=null)return false;56         if(getClass()!=obj.getClass())return false;57         Account other =(Account) obj;58         if(other.name==name&&other.balance==balance)return true;59         else return false;60     }61 }

 

java中線程的同步

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.