1. 程式人生 > >synchronized關鍵字鎖住的是物件還是程式碼塊

synchronized關鍵字鎖住的是物件還是程式碼塊

test開始..
test結束..
test開始..
test結束..
test開始..
test結束..

第一段程式碼鎖住了Sync這個類物件(取決於static關鍵字),而第二段也是鎖住了Sync這個類物件,取決於synchronize(clock)中的clock。而第三段程式碼執行結果就是錯誤的,因為每次都鎖住了新建的物件。

class Sync {  

    public static synchronized void test() {  
        //synchronized (Sync.class) {  
            System.out.println("test開始.."
); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("test結束.."); //} } } class MyThread extends Thread { public void run() { Sync sync = new
Sync(); sync.test(); } } public class Main { public static void main(String[] args) { for (int i = 0; i < 3; i++) { Thread thread = new MyThread(); thread.start(); } } }
class Sync {  

    public void test() {  
        synchronized
(Sync.class) { System.out.println("test開始.."); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("test結束.."); } } } class MyThread extends Thread { public void run() { Sync sync = new Sync(); sync.test(); } } public class Main { public static void main(String[] args) { for (int i = 0; i < 3; i++) { Thread thread = new MyThread(); thread.start(); } } }
class Sync {  

    public synchronized  void test() {  
        //synchronized (Sync.class) {  
            System.out.println("test開始..");  
            try {  
                Thread.sleep(1000);  
            } catch (InterruptedException e) {  
                e.printStackTrace();  
            }  
            System.out.println("test結束..");  
        //}  
    }  
}  

class MyThread extends Thread {  

    public void run() {  
        Sync sync = new Sync();  
        sync.test();  
    }  
}  

public class Main {  

    public static void main(String[] args) {  
        for (int i = 0; i < 3; i++) {  
            Thread thread = new MyThread();  
            thread.start();  
        }  
    }  
}