1.addShutDownHook(thread1)意思是指thread1是jvm中止前最後執行的線程,不管前面有多少線程,這一線程都是最後執行的。java
package runtime; public class ShutdownHook { public static void main(String[] args) { Thread t1 = new Thread(){ @Override public void run() { System.out.println("thread1");; } }; Thread t2 = new Thread(){ @Override public void run() { System.out.println("thread2");; } }; Runtime.getRuntime().addShutdownHook(new Thread(){ @Override public void run() { System.out.println("shutdown");; } }); t1.start(); t2.start(); } }
上面代碼會輸出thread1app
thread2jvm
shutdownide
或thread2spa
thread1線程
shutdowncode
2.Thread.currentThread().join(), thread1.join()本意現指先執行thread1,再執行其餘線程。用在當前前程時,代表當前線程一直等待下去,只有當前線程死掉,纔會退出執行當前線程。具體解釋參見get
http://stackoverflow.com/questions/5999595/thread-join-on-itselfit
原解釋以下:io
It happens out that the join()
method uses the isAlive()
method to determine when to return from the join()
method. In the current implementation, it also does not check to see if the thread is joining itself.
In other words, the join()
method returns when and only when the thread is no longer alive. This will have the effect of waiting forever.