1. 程式人生 > >Java內建鎖的簡單認識

Java內建鎖的簡單認識

        多執行緒開發離不開鎖機制,現在的Java語言中,提供了2種鎖,一種是語言特性提供的內建鎖,還有一種是 java.util.concurrent.locks 包中的鎖,這篇文章簡單整理一下內建鎖的知識點。

內建鎖在Java語言中的表現:

        多執行緒的鎖,其實本質上就是給一塊記憶體空間的訪問新增訪問許可權,因為Java中是沒有辦法直接對某一塊記憶體進行操作的,又因為Java是面向物件的語言,一切皆物件,所以具體的表現就是某一個物件承擔鎖的功能,每一個物件都可以是一個鎖。內建鎖,使用方式就是使用 synchronized 關鍵字,synchronized 方法或者 synchronized 程式碼塊。

每一種 synchronized 寫法的鎖是哪個物件:

1、指定當前物件加鎖:

    private synchronized void function() {
        //TODO execute something
    }

2、指定當前類的Class物件加鎖:

    private static synchronized void function() {
        //TODO execute something
    }


注意此處的 static 關鍵字。 

3、指定任意物件加鎖:

private void function() {
    synchronized
(object) { //TODO execute something } }


此時,這段同步程式碼塊的鎖加在object物件上面。該物件可以是當前物件(object == this),也可以是當前類的Class物件(object == MyClass.class)。

簡單驗證一下:

現有如下的類:

public class SynchronizedTest {
    private Object lock = new Object();

    public void synchronizedBlockOnObject(long executeTime) {
        
synchronized (lock) { System.out.println(Thread.currentThread().getName() + " -> start synchronizedBlockOnObject"); doSomething(executeTime); System.out.println(Thread.currentThread().getName() + " -> end synchronizedBlockOnObject"); } } public void synchronizedBlockOnThis(long executeTime) { synchronized (this) { System.out.println(Thread.currentThread().getName() + " -> start synchronizedBlockOnThis"); doSomething(executeTime); System.out.println(Thread.currentThread().getName() + " -> end synchronizedBlockOnThis"); } } public void synchronizedBlockOnClass(long executeTime) { synchronized (SynchronizedTest.class) { System.out.println(Thread.currentThread().getName() + " -> start synchronizedBlockOnClass"); doSomething(executeTime); System.out.println(Thread.currentThread().getName() + " -> end synchronizedBlockOnClass"); } } public synchronized void synchronizedMethodOnThis(long executeTime) { System.out.println(Thread.currentThread().getName() + " -> start synchronizedMethodOnThis"); doSomething(executeTime); System.out.println(Thread.currentThread().getName() + " -> end synchronizedMethodOnThis"); } public static synchronized void synchronizedMethodOnClass(long executeTime) { System.out.println(Thread.currentThread().getName() + " -> start synchronizedMethodOnClass"); doSomething(executeTime); System.out.println(Thread.currentThread().getName() + " -> end synchronizedMethodOnClass"); } private static void doSomething(long executeTime) { try { Thread.sleep(executeTime); } catch (InterruptedException e) { e.printStackTrace(); } } }

1、static synchronized 方法 和 synchronized (MyClass.class) {} 同步程式碼塊的鎖都加在 MyClass.class 物件上面:

public static void main(String[] args) {
        SynchronizedTest synchronizedTest = new SynchronizedTest();
        
        new Thread(new Runnable() {
            @Override
            public void run() {
                SynchronizedTest.synchronizedMethodOnClass(3000);
            }
        }, "Thread static synchronized method").start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                synchronizedTest.synchronizedBlockOnClass(2000);
            }
        }, "Thread synchronized block on Class").start();
    }


執行結果如下:

Thread static synchronized method -> start synchronizedMethodOnClass
Thread static synchronized method -> end synchronizedMethodOnClass
Thread synchronized block on Class -> start synchronizedBlockOnClass
Thread synchronized block on Class -> end synchronizedBlockOnClass


說明當執行緒 Thread static synchronized method 進入方法 synchronizedMethodOnClass 的時候,執行緒Thread synchronized block on Class 是不能進入synchronizedBlockOnClass 程式碼塊的。

2、非 static 的 synchronized 方法和 synchronized (this) {} 同步程式碼塊的鎖都加在當前物件上面:

public static void main(String[] args) {
    SynchronizedTest synchronizedTest = new SynchronizedTest();

    new Thread(new Runnable() {
        @Override
        public void run() {
            synchronizedTest.synchronizedMethodOnThis(3000);
        }
    }, "Thread non-static synchronized method").start();
    new Thread(new Runnable() {
        @Override
        public void run() {
            synchronizedTest.synchronizedBlockOnThis(2000);
        }
    }, "Thread synchronized block on this").start();
}



執行結果如下:

Thread non-static synchronized method -> start synchronizedMethodOnThis
Thread non-static synchronized method -> end synchronizedMethodOnThis
Thread synchronized block on this -> start synchronizedBlockOnThis
Thread synchronized block on this -> end synchronizedBlockOnThis


說明當執行緒 Thread non-static synchronized method 進入方法 synchronizedMethodOnThis 的時候,執行緒Thread synchronized block on this 是不能進入synchronizedBlockOnThis 程式碼塊的。

3、當鎖加在 MyClass.class 、 this 、 任意物件,這三種情況,起不到任何同步作用:

    public static void main(String[] args) {
        SynchronizedTest synchronizedTest = new SynchronizedTest();

        new Thread(new Runnable() {
            @Override
            public void run() {
                synchronizedTest.synchronizedMethodOnThis(3000);
            }
        }, "Thread non-static synchronized method").start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                SynchronizedTest.synchronizedMethodOnClass(2000);
            }
        }, "Thread static sybchronized method").start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                synchronizedTest.synchronizedBlockOnObject(4000);
            }
        }, "Thread sybchronized block on other Object").start();
    }


執行結果如下:

Thread non-static synchronized method -> start synchronizedMethodOnThis
Thread static sybchronized method -> start synchronizedMethodOnClass
Thread sybchronized block on other Object -> start synchronizedBlockOnObject
Thread static sybchronized method -> end synchronizedMethodOnClass
Thread non-static synchronized method -> end synchronizedMethodOnThis
Thread sybchronized block on other Object -> end synchronizedBlockOnObject


說明當鎖沒有加在同一個物件上的時候,起不到執行緒間的同步作用。

Object中對內建鎖進行操作的一些方法:

wait()系列:

wait()系列方法的作用是:使當前已經獲得該物件鎖的執行緒進入等待狀態,並且釋放該物件的鎖。

notify()系列:

notify()系列方法的作用是:喚醒那些正在等待該物件鎖的執行緒,使其繼續執行。

基於wait() notify()機制,我們可以實現一個簡易的生產者-消費者模型。

大體思路如下,一個生產者執行緒負責向一個倉庫中存放(put)物品,一個消費者執行緒負責從倉庫中取出(get)物品。

程式碼如下:

public class Warehouse {

    private Queue<Integer> queue;
    private int capacity;

    public Warehouse(int capacity) {
        this.capacity = capacity;
        queue = new LinkedList();
    }

    public synchronized void put(int num) {
        if (queue.size() >= capacity) {
            try {
                System.out.println(Thread.currentThread().getName() + " , put full wait");
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        queue.add(num);
        System.out.println(Thread.currentThread().getName() + " , put : " + num + "  , queue -> " + queue);
        notifyAll();
    }

    public synchronized int get() {
        if (queue.isEmpty()) {
            try {
                System.out.println(Thread.currentThread().getName() + " , get empty wait");
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        int num = queue.poll();
        System.out.println(Thread.currentThread().getName() + " , get : " + num + "  , queue -> " + queue);
        notifyAll();
        return num;
    }
}
    public static void main(String[] args) {
        Warehouse warehouse = new Warehouse(4);
        Random random = new Random();

        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    warehouse.put(random.nextInt(10));
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }, "生產者-01").start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    warehouse.get();
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }, "消費者-01").start();
    }


執行結果如下:

生產者-01 , put : 5  , queue -> [5]
消費者-01 , get : 5  , queue -> []
生產者-01 , put : 7  , queue -> [7]
消費者-01 , get : 7  , queue -> []
生產者-01 , put : 9  , queue -> [9]
生產者-01 , put : 7  , queue -> [9, 7]
消費者-01 , get : 9  , queue -> [7]
生產者-01 , put : 0  , queue -> [7, 0]
生產者-01 , put : 5  , queue -> [7, 0, 5]
消費者-01 , get : 7  , queue -> [0, 5]
生產者-01 , put : 9  , queue -> [0, 5, 9]
生產者-01 , put : 6  , queue -> [0, 5, 9, 6]
消費者-01 , get : 0  , queue -> [5, 9, 6]
生產者-01 , put : 4  , queue -> [5, 9, 6, 4]
生產者-01 , put full wait
消費者-01 , get : 5  , queue -> [9, 6, 4]
生產者-01 , put : 6  , queue -> [9, 6, 4, 6]
生產者-01 , put full wait
消費者-01 , get : 9  , queue -> [6, 4, 6]
生產者-01 , put : 2  , queue -> [6, 4, 6, 2]
生產者-01 , put full wait
消費者-01 , get : 6  , queue -> [4, 6, 2]
生產者-01 , put : 9  , queue -> [4, 6, 2, 9]
生產者-01 , put full wait
消費者-01 , get : 4  , queue -> [6, 2, 9]
生產者-01 , put : 7  , queue -> [6, 2, 9, 7]
生產者-01 , put full wait
消費者-01 , get : 6  , queue -> [2, 9, 7]
生產者-01 , put : 2  , queue -> [2, 9, 7, 2]