Skip to main content

锁工具类LockSupport

huhxLess than 1 minutejavaConcurrency-ToolkitConcurrency

使用

public class LockSupportMain {
    public static void main(String[] args) {
        var thread = new Thread(() -> {
            for (int i = 0; i < 3; i++) {
                System.out.printf("i = %d, time = %s\n", i, LocalDateTime.now());
                secondsSleep(1);
                if (i == 1) {
                    LockSupport.park();
                }
            }
        });
        thread.start();

        secondsSleep(4);
        System.out.println("After 4 seconds");
        LockSupport.unpark(thread);
    }

    private static void secondsSleep(int seconds) {
        try {
            TimeUnit.SECONDS.sleep(seconds);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
}

输出结果

i = 0, time = 2023-09-07T08:25:32.929474
i = 1, time = 2023-09-07T08:25:33.944046
After 4 seconds
i = 2, time = 2023-09-07T08:25:36.917732

unpark可以在park之前调用,去掉上述的secondsSleep(9)代码,也就是:

thread.start();
LockSupport.unpark(thread);

输出

i = 0, time = 2023-09-07T08:26:06.781756
i = 1, time = 2023-09-07T08:26:07.800623
i = 2, time = 2023-09-07T08:26:08.805705

分析

FAQ

总结

参考