LockSupport原理分析

一. LockSupport類介紹

LockSupport類能夠阻塞當前線程以及喚醒指定被阻塞的線程。主要是經過park()和unpark(thread)方法來實現阻塞和喚醒線程的操做的。java

每一個線程都有一個許可(permit),permit只有兩個值1和0,默認是0。多線程

  1. 當調用unpark(thread)方法,就會將thread線程的許可permit設置成1(注意屢次調用unpark方法,不會累加,permit值仍是1)。
  2. 當調用park()方法,若是當前線程的permit是1,那麼將permit設置爲0,並當即返回。若是當前線程的permit是0,那麼當前線程就會阻塞,直到別的線程將當前線程的permit設置爲1.park方法會將permit再次設置爲0,並返回。

注意:由於permit默認是0,因此一開始調用park()方法,線程一定會被阻塞。調用unpark(thread)方法後,會自動喚醒thread線程,即park方法當即返回。dom

二. LockSupport類示例

import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.locks.LockSupport;

// 簡易的先進先出非重入鎖
class FIFOMutex {
    //
    private final AtomicBoolean locked = new AtomicBoolean(false);
    // 記錄等待線程隊列
    private final Queue<Thread> waiters = new ConcurrentLinkedQueue<Thread>();

    public void lock() {
        boolean wasInterrupted = false;
        Thread current = Thread.currentThread();
        waiters.add(current);

        // 若是當前線程不是等待線程隊列第一個,或者locked狀態已是true,那麼當前線程就要等待
        while (waiters.peek() != current || !locked.compareAndSet(false, true)) {
            System.out.println(Thread.currentThread().getName()+"  park start");
            LockSupport.park(this);
            System.out.println(Thread.currentThread().getName()+"  park end");
            // 等待線程的中斷線程標誌位爲true,就設置wasInterrupted爲true
            if (Thread.interrupted())
                wasInterrupted = true;
        }

        // 移除第一個元素。當前線程就是第一個元素,由於while判斷條件
        waiters.remove();
        // 若是wasInterrupted爲true,當前線程發出中斷請求
        if (wasInterrupted)
            current.interrupt();
        System.out.println(Thread.currentThread().getName()+" lock end" );
    }

    // 喚醒可能等待的線程
    public void unlock() {
        System.out.println(Thread.currentThread().getName()+"  unpark start ");
        // 將locked設置爲false
        locked.set(false);
        // 喚醒當前線程隊列中第一個元素
        LockSupport.unpark(waiters.peek());
        System.out.println(Thread.currentThread().getName()+"  unpark end ");
    }
}


public class LockSupportTest {

    public static void startThread(String name, final FIFOMutex clock, final CountDownLatch countDownLatch) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                clock.lock();
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    System.out.println(Thread.currentThread().getName()+"  finally");
                    countDownLatch.countDown();
                    clock.unlock();
                }
            }
        }, name).start();
    }

    public static void main(String[] args) {
        FIFOMutex clock = new FIFOMutex();
        CountDownLatch countDownLatch = new CountDownLatch(3);
        startThread("t111", clock, countDownLatch);
        startThread("t222", clock, countDownLatch);
        startThread("t333", clock, countDownLatch);

        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("main end");
    }
}

從這個例子中能夠看出,park方法會阻塞當前線程,unpark(thread)方法,會當即喚醒被阻塞的線程,讓它從park方法處繼續執行。ide

三. LockSupport源碼註釋

package java.util.concurrent.locks;
import sun.misc.Unsafe;

import java.util.concurrent.Semaphore;
import java.util.concurrent.ThreadLocalRandom;

/**
 * 提供阻塞線程和喚醒線程的方法。
 */
public class LockSupport {
    // 構造函數是私有的,因此不能在外部實例化
    private LockSupport() {}

    // 用來設置線程t的parkBlocker屬性。此對象在線程受阻塞時被記錄,以容許監視工具和診斷工具肯定線程受阻塞的緣由。
    private static void setBlocker(Thread t, Object arg) {
        UNSAFE.putObject(t, parkBlockerOffset, arg);
    }

    // 喚醒處於阻塞狀態下的thread線程
    public static void unpark(Thread thread) {
        // 當線程不爲null時調用
        if (thread != null)
            // 經過UNSAFE的unpark喚醒被阻塞的線程
            UNSAFE.unpark(thread);
    }

    // 阻塞當前線程
    public static void park(Object blocker) {
        Thread t = Thread.currentThread();
        // 設置線程t的parkBlocker屬性,用於記錄線程阻塞狀況
        setBlocker(t, blocker);
        // 經過UNSAFE的park方法阻塞線程
        UNSAFE.park(false, 0L);
        setBlocker(t, null);
    }

    // 阻塞當前線程nanos納秒時間,超出時間線程就會被喚醒返回
    public static void parkNanos(Object blocker, long nanos) {
        if (nanos > 0) {
            Thread t = Thread.currentThread();
            setBlocker(t, blocker);
            UNSAFE.park(false, nanos);
            setBlocker(t, null);
        }
    }
    // 阻塞當前線程,超過deadline日期線程就會被喚醒返回
    public static void parkUntil(Object blocker, long deadline) {
        Thread t = Thread.currentThread();
        setBlocker(t, blocker);
        UNSAFE.park(true, deadline);
        setBlocker(t, null);
    }

    // 獲取線程t的parkBlocker屬性
    public static Object getBlocker(Thread t) {
        if (t == null)
            throw new NullPointerException();
        return UNSAFE.getObjectVolatile(t, parkBlockerOffset);
    }

    // 阻塞當前線程,不設置parkBlocker屬性
    public static void park() {
        UNSAFE.park(false, 0L);
    }

    public static void parkNanos(long nanos) {
        if (nanos > 0)
            UNSAFE.park(false, nanos);
    }

    public static void parkUntil(long deadline) {
        UNSAFE.park(true, deadline);
    }

    static final int nextSecondarySeed() {
        int r;
        Thread t = Thread.currentThread();
        if ((r = UNSAFE.getInt(t, SECONDARY)) != 0) {
            r ^= r << 13;   // xorshift
            r ^= r >>> 17;
            r ^= r << 5;
        }
        else if ((r = ThreadLocalRandom.current().nextInt()) == 0)
            r = 1; // avoid zero
        UNSAFE.putInt(t, SECONDARY, r);
        return r;
    }

    // Hotspot implementation via intrinsics API
    private static final Unsafe UNSAFE;
    private static final long parkBlockerOffset;
    private static final long SEED;
    private static final long PROBE;
    private static final long SECONDARY;
    static {
        try {
            UNSAFE = Unsafe.getUnsafe();
            Class<?> tk = Thread.class;
            parkBlockerOffset = UNSAFE.objectFieldOffset
                (tk.getDeclaredField("parkBlocker"));
            SEED = UNSAFE.objectFieldOffset
                (tk.getDeclaredField("threadLocalRandomSeed"));
            PROBE = UNSAFE.objectFieldOffset
                (tk.getDeclaredField("threadLocalRandomProbe"));
            SECONDARY = UNSAFE.objectFieldOffset
                (tk.getDeclaredField("threadLocalRandomSecondarySeed"));
        } catch (Exception ex) { throw new Error(ex); }
    }

}

LockSupport的源碼比較簡單,主要就是park系列阻塞當前線程的方法,以及unpark喚醒某個線程的方法。函數

注意,park系列的方法就是直接阻塞當前線程的,因此不須要線程變量參數。而unpark方法是喚醒對應線程的,因此必須傳遞線程變量thread。

Java多線程詳細介紹這篇文章中,咱們介紹了線程一共有六種狀態,而park系列方法線程進入兩種狀態:WAITING等待狀態或TIMED_WAITING等待狀態。這兩種狀態都會使線程阻塞在當前位置。
那麼怎麼喚醒這兩種狀態的線程呢?工具

對於WAITING等待狀態有兩種喚醒方式:this

  1. 調用對應的喚醒方法。這裏就是LockSupport的unpark方法。
  2. 調用該線程變量的interrupt()方法,會喚醒該線程,並拋出InterruptedException異常。

對於TIMED_WAITING等待狀態來講,它比WAITING狀態多了一種喚醒方式,就是超過規定時間,那麼線程會自動醒來。atom

相關文章
相關標籤/搜索