#大學#Java多線程學習02(線程同步)

來源:互聯網
上載者:User

*所謂同步機制是指兩個線程同時操作一個對象,應該保持對象資料的統一性和整體性。

*Java語言中有兩種同步形式,即同步方法和同步代碼塊。

1,同步方法

同步方法將訪問這個資源的方法都標記為synchronized,這樣在需要調用這個方法的線程執行完之前,其它調用該方法的線程都會被阻塞。

synchronized void sum(){…}

synchronized void max(){…}

*建立兩個線程的例子

import java.util.logging.Level;
import java.util.logging.Logger;

public class SyncThread extends Thread {
    private char cha;
    public SyncThread(char cha){
        this.cha=cha;
    }
    public void run(){
        PrintClass.printch(cha);
        System.out.println();
    }
    public static void main(String[] args){
        SyncThread t1=new SyncThread('A');
        SyncThread t2=new SyncThread('B');
        t1.start();
        t2.start();
    }
}
class PrintClass{
    public static void printch(char cha){
        for(int i=0;i<5;i++){
            try {
                Thread.sleep(1000);
            } catch (InterruptedException ex) {
                Logger.getLogger(PrintClass.class.getName()).log(Level.SEVERE, null, ex);
            }
            System.out.print(cha);
        }
    }
}

*同步塊

Java語言中同步的設定不只應用於同步方法,也可以設定程式的某個程式碼片段為同步地區。

文法格式為:

synchronized(someobject){…代碼…}

 

聯繫我們

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