首页 > 代码库 > 线程阻塞工具类:LockSupport(读书笔记)

线程阻塞工具类:LockSupport(读书笔记)

 他可以在线程任意位置让线程阻塞,
LockSupport的静态方法park()可以阻塞当前线程,类似的还有parkNanos() ParkUntil()等,他们实现了一个限时等待
public class LockSupportDemo {
    public static Object u = 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);
        }

        public void run() {
            synchronized (u) {
                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();
    }
}
     我们可以使用park()和unpark()方法替换掉以往的suspend()和resume()方法.当然我们依然无法保证unpark()方法发生在park(0方法之后,当时执行这段代码,你会发现,它自始至终都可以正常结束,不会因为park()方法二导致线程永久性的挂起,
     这是因为LockSupport类使用类似信号量的机制,他为每一个线程准备了一个许可.这个特点使得:即使unpark()操作发生在park()之前,它也可以使下一次的park()操作立即返回.这也就是上述代码可顺利结束的主要原因.
     出来有定时阻塞的功能外,还支持中断影响,但是和其他接收中断函数不一样,他不会抛出InterruptedException异常,他只会默默的返回,但是我们可以从Thread.Interrupted()等方法获得中断标记.
public class LockSupportIntDemo {
    public static Object u = 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);
        }

        public void run() {
            synchronized (u) {
                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();
        Thread.sleep(100);
        t2.start();
        t1.interrupt();
        LockSupport.unpark(t2);
    }
}
 

线程阻塞工具类:LockSupport(读书笔记)