Java多線程的同步問題

來源:互聯網
上載者:User

這裡我們在run()方法中加入了synchronized關鍵字,希望能對run方法進行互斥訪問,但結果並不如我們希望那樣,這是因為這裡synchronized鎖住的是this對象,即當前運行線程對象本身。代碼中建立了10個線程,而每個線程都持有this對象的對象鎖,這不能實現線程的同步。

    代碼
    package com.vista;
    class MyThread implements java.lang.Runnable {
     private int threadId;

     public MyThread(int id) {
      this.threadId = id;
     }

     @Override
     public synchronized void run() {
      for (int i = 0; i < 100; ++i) {
       System.out.println("Thread ID: " + this.threadId + " : " + i);
      }
     }
    }

    public class ThreadDemo {
     /**
      * @param args
      * @throws InterruptedException
      */
     public static void main(String[] args) throws InterruptedException {
      for (int i = 0; i < 10; ++i) {
       new Thread(new MyThread(i)).start();
       Thread.sleep(1);
      }
     }
    }

    從上述程式碼片段可以得知,要想實現線程的同步,則這些線程必須去競爭一個唯一的共用的對象鎖。

    基於這種思想,我們將第一段代碼修改如下所示,在建立啟動線程之前,先建立一個線程之間競爭使用的Object對象,然後將這個Object對象的引用傳遞給每一個線程對象的lock成員變數。這樣一來,每個線程的lock成員都指向同一個Object對象。我們在run方法中,對lock對象使用synchronzied塊進行局部封鎖,這樣就可以讓線程去競爭這個唯一的共用的對象鎖,從而實現同步。

    代碼
    package com.vista;

    class MyThread implements java.lang.Runnable {
     private int threadId;
     private Object lock;

     public MyThread(int id, Object obj) {
      this.threadId = id;
      this.lock = obj;
     }

     @Override
     public void run() {
      synchronized (lock) {
       for (int i = 0; i < 100; ++i) {
;       System.out.println("Thread ID: " + this.threadId + " : " + i);
       }
      }
     }
    }

 

    public class ThreadDemo {
     /**
      * @param args
      * @throws InterruptedException
      */
     public static void main(String[] args) throws InterruptedException {
      Object obj = new Object();
      for (int i = 0; i < 10; ++i) {
       new Thread(new MyThread(i, obj)).start();
       Thread.sleep(1);
      }
     }
    }

    從第二段代碼可知,同步的關鍵是多個線程對象競爭同一個共用資源即可,上面的代碼中是通過外部建立共用資源,然後傳遞到線程中來實現。我們也可以利用類成員變數被所有類的執行個體所共用這一特性,因此可以將lock用靜態成員對象來實現,代碼如下所示:

    代碼
    package com.vista;

    class MyThread implements java.lang.Runnable {
     private int threadId;
     private static Object lock = new Object();

     public MyThread(int id) {
      this.threadId = id;
     }

     @Override
     public void run() {
      synchronized (lock) {
       for (int i = 0; i < 100; ++i) {
        System.out.println("Thread ID: " + this.threadId + " : " + i);
       }
      }
     }
    }

    public class ThreadDemo {
     /**
      * @param args
      * @throws InterruptedException
      */
     public static void main(String[] args) throws InterruptedException {
      for (int i = 0; i < 10; ++i) {
       new Thread(new MyThread(i)).start();
       Thread.sleep(1);
      }
     }
    }

    再來看第一段代碼,執行個體方法中加入sychronized關鍵字封鎖的是this對象本身,而在靜態方法中加入sychronized關鍵字封鎖的就是類本身。靜態方法是所有類執行個體對象所共用的,因此線程對象在訪問此靜態方法時是互斥訪問的,從而可以實現線程的同步,代碼如下所示:

    代碼
    package com.vista;

    class MyThread implements java.lang.Runnable{
     private int threadId;

 

     public MyThread(int id) {
      this.threadId = id;
     }

     @Override
     public void run() {
      taskHandler(this.threadId);
     }

     private static synchronized void taskHandler(int threadId) {
      for (int i = 0; i < 100; ++i) {
       System.out.println("Thread ID: " + threadId + " : " + i);
      }
     }
    }

    public class ThreadDemo {
     /**
      * @param args
      * @throws InterruptedException
      */
     public static void main(String[] args) throws InterruptedException {
      for (int i = 0; i < 10; ++i) {
       new Thread(new MyThread(i)).start();
       Thread.sleep(1);
      }
     }
    }

聯繫我們

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