1. 程式人生 > >synchronized關鍵字加到static靜態方法和非static靜態方法區別

synchronized關鍵字加到static靜態方法和非static靜態方法區別

synchronized關鍵字加到static靜態方法上是給Class類上鎖
而加到非static靜態方法是給物件加鎖
為了驗證不是同一個鎖 驗證程式碼如下

package com.test.Thread.t10;

/**
 * @author admin
 * 2017年4月20日
 */
public class Service {

    synchronized public static void printA(){
        try {
            System.out.println("執行緒名稱為:"+Thread.currentThread().getName()+"在  "
+System.currentTimeMillis()+" 進入pringA()"); Thread.sleep(3000); System.out.println("執行緒名稱為:"+Thread.currentThread().getName()+"在 "+System.currentTimeMillis()+" 離開pringA()"); } catch (Exception e) { e.printStackTrace(); } } synchronized public
static void printB(){ try { System.out.println("執行緒名稱為:"+Thread.currentThread().getName()+"在 "+System.currentTimeMillis()+" 進入printB()"); System.out.println("執行緒名稱為:"+Thread.currentThread().getName()+"在 "+System.currentTimeMillis()+" 離開printB()"); } catch (Exception e) { e.printStackTrace(); } } // synchronized public void printC(){
// try { // System.out.println("執行緒名稱為:"+Thread.currentThread().getName()+"在 "+System.currentTimeMillis()+" 進入printC()"); // // System.out.println("執行緒名稱為:"+Thread.currentThread().getName()+"在 "+System.currentTimeMillis()+" 離開printC()"); // } catch (Exception e) { // e.printStackTrace(); // } // } public static void main(String[] args) { Service s=new Service(); ThreadA a=new ThreadA(s); a.setName("A"); a.start(); ThreadB b=new ThreadB(s); b.setName("B"); b.start(); // // ThreadC c=new ThreadC(s); // c.setName("C"); // c.start(); } } class ThreadA extends Thread{ private Service s; public ThreadA(Service s) { super(); this.s = s; } @Override public void run() { s.printA(); } } class ThreadB extends Thread{ private Service s; public ThreadB(Service s) { super(); this.s = s; } @Override public void run() { s.printB(); } } // //class ThreadC extends Thread{ // private Service s; // // public ThreadC(Service s) { // super(); // this.s = s; // } // @Override // public void run() { // s.printC(); // } //}

執行結果如下
這裡寫圖片描述
同步效果執行,執行後在執行第二個 如果加到非static方法就不一樣了 是非同步的效果
放開註釋的部分程式碼 再次執行 效果如下
這裡寫圖片描述

這裡非同步的原因是因為持有不同的鎖,一個是物件鎖 ,一個是class鎖 而calss鎖可以對類的所有例項起作用