J.U.C Lock LockSupport

LockSupport既弥补了resume()在suspend()之前发生,也不需要向Object.wait()那样需要获取对象的锁,也不会抛出InterruptedException。
LockSupport采用类似信号量的机制为每个线程准备了一个许可。如果许可可用,park函数立即返回,如果许可不可用则阻塞,而unpark()则可以使许可可用(因此可见,许可可用park返回,许可不可用unpark使其可用park返回)。

示例1

import java.util.concurrent.locks.LockSupport;

public class LockSupportDemo {

    public static Object lock = new Object();
    static ChangeObjectThread t1 = new ChangeObjectThread("t1");
    static ChangeObjectThread t2 = new ChangeObjectThread("t2");

    public static class ChangeObjectThread extends Thread {
        public ChangeObjectThread(String name) {
            super.setName(name);
        }

        @Override
        public void run() {
            synchronized (lock) {
                System.out.println("in " + getName());
                LockSupport.park();
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        t1.start();
        Thread.sleep(100);
        t2.start();
        LockSupport.unpark(t1);
        LockSupport.unpark(t2);
        t1.join();
        t2.join();
    }
}

示例2 响应中断

LockSupport支持中断影响,但不会抛出InterruptedException异常。

import java.util.concurrent.locks.LockSupport;

public class LockSupportIntDemo {

    public static Object lock = new Object();
    static ChangeObjectThread t1 = new ChangeObjectThread("t1");
    static ChangeObjectThread t2 = new ChangeObjectThread("t2");

    public static class ChangeObjectThread extends Thread {
        public ChangeObjectThread(String name) {
            super.setName(name);
        }

        @Override
        public void run() {
            synchronized (lock) {
                System.out.println("in " + getName());
                LockSupport.park();
                if (Thread.interrupted()) {
                    System.out.println(getName()+"被中断了");
                }
                System.out.println(getName()+"执行结束");
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        t1.start();
        t1.interrupt();
        Thread.sleep(100);
        t2.start();
        LockSupport.unpark(t2);
    }
}

你可能感兴趣的:(J.U.C Lock LockSupport)