Java LockSupport 几种唤醒机制

Java About 843 words

暂停线程

LockSupport使用park系列方法底层调用C++代码来暂停线程。

唤醒线程

LockSupportpark方法上有一段注释:

Some other thread invokes unpark with the current thread as the target; or Some other thread interrupts the current thread; or The call spuriously (that is, for no reason) returns.

方法一

使用LockSupportunpark方法。

方法二

使用LockSupportparkUntil方法。

方法三

使用线程的interrupt也能唤醒LockSupportpark方法。

public class LockSupportInterruptDemo {

    public static void main(String[] args) {
        Thread thread = new Thread(() -> {
            LockSupport.park();
            System.out.println("unpark");
        });
        thread.start();

        new Thread(() -> {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            thread.interrupt();
        }).start();
    }

}
Views: 539 · Posted: 2023-12-08

————        END        ————

Give me a Star, Thanks:)

https://github.com/fendoudebb/LiteNote

扫描下方二维码关注公众号和小程序↓↓↓

扫描下方二维码关注公众号和小程序↓↓↓


Today On History
Browsing Refresh