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之前還是之後,作用是一樣的,都會重新喚醒線程;