Android多線程研究(3)線程同步和互斥及死結

來源:互聯網
上載者:User

為什麼會有線程同步的概念呢?為什麼要同步?什麼是線程同步?先看一段代碼:

package com.maso.test;        public class ThreadTest2 implements Runnable{      private TestObj testObj = new TestObj();                public static void main(String[] args) {          ThreadTest2 tt = new ThreadTest2();          Thread t1 = new Thread(tt, "thread_1");          Thread t2 = new Thread(tt, "thread_2");          t1.start();          t2.start();      }            @Override    public void run() {                        for(int j = 0; j < 10; j++){              int i = fix(1);              try {                  Thread.sleep(1);              } catch (InterruptedException e) {                  e.printStackTrace();              }                                System.out.println(Thread.currentThread().getName() + " :  i = " + i);          }                    }                public int fix(int y){          return testObj.fix(y);      }                public class TestObj{          int x = 10;                        public int fix(int y){              return x = x - y;          }      }                      }

輸出結果後,就會發現變數x被兩個線程同時操作,這樣就很容易導致誤操作。如何才能解決這個問題呢?用線程的同步技術,加上synchronized關鍵字

public synchronized int fix(int y){

return testObj.fix(y);

}

加上同步後,就可以看到有序的從9輸出到-10.

如果加到TestObj類的fix方法上能不能實現同步呢?

public class TestObj{

int x = 10;

public synchronized int fix(int y){

return x = x - y;

}

}

如果將synchronized加到方法上則等價於

synchronized(this){

}

聯繫我們

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