不是每个try后的finally都会执行。
看看下面的代码,
| public class DaemonThread extends Object implements Runnable { public void run() { System.out.println("entering run()"); int i = 0; try { System.out.println("in run() - currentThread()=" + Thread.currentThread()); while (true) { try { Thread.sleep(500); } catch (InterruptedException x) { } System.out.println("in run() - woke up again " + (++i)); } } finally { System.out.println("leaving run()"); } } } |
| public class DaemonThreadMain extends Object { public static void main(String[] args) { System.out.println("entering main()"); Thread t = new Thread(new DaemonThread()); t.setDaemon(true); t.start(); try { Thread.sleep(3000); } catch (InterruptedException x) { } System.out.println("leaving main()"); } } |
得到的结果里,会发现并没有前一个DaemonThread类的finally的打印结果。Daemon线程区别一般线程之处是:主程序一旦结束,Daemon线程就会结束,并且也不会调用finally里的语句。
Any Java thread can be a daemon thread. Daemon threads are service providers for other threads running in the same process as the daemon thread. For example, the HotJava browser uses up to four daemon threads named "Image Fetcher" to fetch images from the file system or network for any thread that needs one. The run() method for a daemon thread is typically an infinite loop that waits for a service request.
When the only remaining threads in a process are daemon threads, the interpreter exits. This makes sense because when only daemon threads remain, there is no other thread for which a daemon thread can provide a service.
To specify that a thread is a daemon thread, call the setDaemon() method with the argument true. To determine if a thread is a daemon thread, use the accessor method isDaemon().




曲目:
受关注文章