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之前还是之后,作用是一样的,都会重新唤醒线程;