JAVA 並發編程-傳統線程互斥技術(Synchronized)(三)

來源:互聯網
上載者:User

標籤:

    

    java線程互斥是為了保證,同一時刻最多隻有一個線程執行該段代碼。那麼它的出現又是為瞭解決什麼問題呢?賬戶存取款,在同一時間段只能讓一個人進行操作。

 

下面來看一個簡單一實例(多線程帶來的問題):

public class TraditionalThreadSynchronized {/** * @param args */public static void main(String[] args) {new TraditionalThreadSynchronized().init();}private void init(){//此方法同時啟動兩個線程,去調用同一個方法的列印名字final Outputer outputer = new Outputer();new Thread(new Runnable(){@Overridepublic void run() {while(true){try {Thread.sleep(10);} catch (InterruptedException e) {e.printStackTrace();}outputer.output("zhangxiaoxiang");}}}).start();new Thread(new Runnable(){@Overridepublic void run() {while(true){try {Thread.sleep(10);} catch (InterruptedException e) {e.printStackTrace();}outputer.output3("lihuoming");}}}).start();}static class Outputer{public void output(String name){int len = name.length();//synchronized (Outputer.class) //{for(int i=0;i<len;i++){System.out.print(name.charAt(i));}System.out.println();//}}}}

列印結果為:




解決以上問題:

 

添加synchronized的關鍵字,即解開注釋即可。

 

列印結果:




總結:

 

當兩個並發線程訪問同一個對象object中的這個synchronized(this)同步代碼塊時,一個時間內只能有一個線程得到執行。另一個線程必須等待當前線程執行完這個代碼塊以後才能執行該代碼塊。即當一個線程訪問object的一個synchronized(this)同步代碼塊時,其他線程對object中所有其它synchronized(this)同步代碼塊的訪問將被阻塞。

注意:要互斥,必須讓鎖子是同一把。以上的demo中,兩個線程都用的是同一個new出來的output,所以output就是同一個對象。

 

詳細內容請參看部落格[原]02____線程的同步(Synchronized)

 

簡答說明:

public class Test implements Runnable {    public int cash = 100;    public synchronized void m() {        System.out.println("m查看賬戶,餘額為"+cash);        try {             Thread.sleep(2000);        } catch (InterruptedException e) {             e.printStackTrace();        }        cash = cash - 100;        System.out.println("cash1 = " + cash);    }    public synchronized void run() {        System.out.println("run查看賬戶,餘額為"+cash);        cash += 1000;        try {            Thread.sleep(5000);         } catch (InterruptedException e) {             e.printStackTrace();         }        System.out.println("cash2 = " + cash);    }    public static void main(String[] args) {        Test test = new Test();        Thread thrad = new Thread(test);        thrad.start();        test.m();    }}

添加synchronized關鍵字後可以看出。只要m或者run進行對賬戶進行操作,不論中途多長時間,或者睡眠多長時間,線程都要執行完這個方法以後才會執行其他的方法。兩個方法都必須加synchronized關鍵字,並且兩者鎖定同一對象(此處鎖定的對象是test對象)。也就是說,只要有一個線程進入test對象的任意一個加了鎖的方法,其他線程就不能訪問這個對象裡加了相同鎖的方法了。




著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

JAVA 並發編程-傳統線程互斥技術(Synchronized)(三)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.