LockSupport

示例用法:

public static void main(String[] args) {
        Thread t = new Thread(()->{
            for (int i = 0; i < 6; i++) {
                System.out.println(i);
                if(i == 3) {
                    LockSupport.park();  //阻塞
                }
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        t.start();

//        LockSupport.unpark(t);

        try {
            TimeUnit.SECONDS.sleep(5);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("after 5 senconds!");

        LockSupport.unpark(t); //把刚刚在i=3阻塞的线程t放行

    }

LockSupport.park() 对应一个LockSupport.unpark(),类似于一个计数

public static void main(String[] args) {
        Thread t = new Thread(()->{
            for (int i = 0; i < 6; i++) {
                System.out.println(i);
                if(i == 3) {
                    LockSupport.park();
                }
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        t.start();

        LockSupport.unpark(t);

//        try {
//            TimeUnit.SECONDS.sleep(5);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
//        System.out.println("after 5 senconds!");
//

    }

上面这样的话,线程就不会阻塞。

你可能感兴趣的:(LockSupport)