LockSupport

65 阅读1分钟

可以用它来阻塞和唤醒线程,notify 不能指定唤醒哪个线程,LockSupport 可以唤醒单个指定线程,notifyAll 可以唤醒全部线程。

如果 t1 线程已经 start 还没执行到 park 方法,而另外的线程已经执行 unpark(t1),那么 t1 不会再被阻塞。

public static void main(String[] args)  {
        Thread parkThread = new Thread(new ParkThread());
        parkThread.start();
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("开始线程唤醒");
        LockSupport.unpark(parkThread);
        System.out.println("结束线程唤醒");
    }

    static class ParkThread implements Runnable{

        @Override
        public void run() {
            for (int i = 0; i < 5; i++) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                if (i == 2) {
                    // 阻塞线程
                    LockSupport.park();
                    // 阻塞 10S
                    //LockSupport.parkNanos(10000000000L);
                }
                System.out.println(i);
            }
        }
    }
// 两个线程打印1A2B3C...26Z
static Thread thread1 = null, thread2 = null;   

public static void main(String[] args)  {
    thread1 = new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 1; i < 27; i++) {
                    System.out.print(i);
                    LockSupport.unpark(thread2);
                    LockSupport.park();

                }
            }
        });

        thread2 = new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 1; i < 27; i++) {
                    LockSupport.park();
                    System.out.println((char) (96 + i));
                    LockSupport.unpark(thread1);

                }
            }
        });
        thread1.start();
        thread2.start();
}