1.unpark在thread start之前调用
public static void main(String[] args) throws InterruptedException{
Thread thread1 = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("thread1 start");
try{
Thread.sleep(2000);
} catch (Exception e){
e.printStackTrace();
}
System.out.println("thread1 run before park");
LockSupport.park();
System.out.println("thread1 run after park");
}
});
LockSupport.unpark(thread1);
thread1.start();
System.out.println("main thread");
}
执行结果:
main thread
thread1 start
thread1 run before park
(程序没有退出,线程1一直挂起)
2.unpark在park之前执行
public static void main(String[] args) throws InterruptedException{
Thread thread1 = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("thread1 start");
try{
Thread.sleep(2000);
} catch (Exception e){
e.printStackTrace();
}
System.out.println("thread1 run before park");
LockSupport.park();
System.out.println("thread1 run after park");
}
});
thread1.start();
LockSupport.unpark(thread1);
System.out.println("main thread");
}
执行结果:
thread1 start
main thread
thread1 run before park
thread1 run after park
3.unpark在park之后执行
public static void main(String[] args) throws InterruptedException{
Thread thread1 = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("thread1 run before park");
LockSupport.park();
System.out.println("thread1 run after park");
}
});
thread1.start();
System.out.println("main thread");
Thread.sleep(3000);
LockSupport.unpark(thread1);
}
执行结果:
main thread
thread1 run before park
thread1 run after park
总结
1.unpark必须在thread start之后才有用,之前调用没有任何效果;
2.thread start之后,unpark在park之前还是之后,作用是一样的,都会重新唤醒线程;
本文通过三个实验深入探讨了Java中LockSupport类的unpark和park方法的使用时机与效果,揭示了线程唤醒的机制。实验表明,unpark必须在线程启动后才能生效,无论是在park前还是后调用,都能成功唤醒线程。
800

被折叠的 条评论
为什么被折叠?



