線程--Java線程的互斥技術

來源:互聯網
上載者:User

標籤:tput   舉例   output   位元組   cep   屬性   載入   test   噁心   

java的多線程互斥主要通過synchronized關鍵字實現。一個線程就是一個執行線索,多個線程可理解為多個執行線索。進程有獨立的記憶體空間,而進程中的線程則是共用資料對象資源。這樣當多個執行線索在CPU的切換下交替執行,就會出現一些噁心的情況,執行的結果也是匪夷所思。第一個線程未執行完,CPU切換到另一個線程執行,由於資料資源共用,將導致程式的執行混亂。解決線程間的互斥主要就是通過synchronized來實現。

下面利用傳智播客裡面的代碼舉例分析:

package com.cqfczc.util;/** * 多線程的互斥技術 * @author zhenliang * */public class ThreadSynchronized {public static void main(String[] args) {new ThreadSynchronized().testThread();}private void testThread(){final OutPutPrinter printer = new OutPutPrinter();new Thread(new Runnable() {@Overridepublic void run() {while (true) {try {Thread.sleep(20);} catch (InterruptedException e) {e.printStackTrace();}printer.printer("風鈴三世愛著猴子");}}}).start();new Thread(new Runnable() {@Overridepublic void run() {while (true) {try {Thread.sleep(20);} catch (InterruptedException e) {e.printStackTrace();}printer.printer("猴子始終喜歡楊嬋");}}}).start();}
     //多線程不適用互斥技術時的有問題代碼class OutPutPrinter{public void printer(String name){if(name == null){throw new NullPointerException("參數不可為空!");}int nameLength = name.length();for(int i=0;i<nameLength;i++){System.out.print(name.charAt(i));}System.out.println();}
          }}

1、自訂的對象作為鎖對象 
實現方式 :synchronized(<自訂鎖對象>){…} 
適用情況:當出現需要在多個類(或者多個類的執行個體)之間進行互斥控制時,需要採用本方法。

class OutPutPrinter{private String lock = "大潑猴";public void printer(String name){if(name == null){throw new NullPointerException("參數不可為空!");}int nameLength = name.length();synchronized(lock){for(int i=0;i<nameLength;i++){System.out.print(name.charAt(i));}System.out.println();}}}

2、以this作為鎖對象 
實現方式:synchronized(this){…},synchronized執行個體方法;
適用情況:適用於使用類的同一個執行個體(對象)作為鎖對象。

        // 同步方法,相當於synchronized(this){}        public synchronized void output2(String name) {            int len = name.length();            for(int i=0; i<len; i++) {                System.out.print(name.charAt(i));            }            System.out.println();        }    

3、以Outputer.class作為鎖對象 
Outputer類的位元組碼對象由jvm自動載入。 
實現方式:synchronized(Outputer.class){…} ,static synchronized方法 
適用情況:適用於整個類的所有對象都需要互斥訪問的情況

        // 靜態同步方法,相當於synchronized(Outputer.class){}        public static synchronized void output3(String name) {            int len = name.length();            for(int i=0; i<len; i++) {                System.out.print(name.charAt(i));            }            System.out.println();        }

總結:同一個類中代碼塊或者方法的互斥,使用this或者類的位元組碼作為對象鎖;當需要在多個類(或者多個類的執行個體)之間進行互斥控制時,使用自訂對象鎖或類位元組碼對象鎖;因為類的位元組碼全世界只有一份,自訂的對象鎖是類內部的一個成員變數,每次建立新對象的時候屬性是一樣的。

 

線程--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.