Java线程之守护线程(Daemon) .
http://blog.csdn.net/mq612/article/details/1520571
守護線程(Daemon)
Java有兩種Thread:“守護線程Daemon”與“用戶線程User”。 我們之前看到的例子都是用戶,守護線程是一種“在后臺提供通用性支持”的線程,它并不屬于程序本體。 從字面上我們很容易將守護線程理解成是由虛擬機(virtual machine)在內部創建的,而用戶線程則是自己所創建的。事實并不是這樣,任何線程都可以是“守護線程Daemon”或“用戶線程User”。他們在幾乎每個方面都是相同的,唯一的區別是判斷虛擬機何時離開: 用戶線程:Java虛擬機在它所有非守護線程已經離開后自動離開。 守護線程:守護線程則是用來服務用戶線程的,如果沒有其他用戶線程在運行,那么就沒有可服務對象,也就沒有理由繼續下去。 setDaemon(boolean on)方法可以方便的設置線程的Daemon模式,true為Daemon模式,false為User模式。setDaemon(boolean on)方法必須在線程啟動之前調用,當線程正在運行時調用會產生異常。isDaemon方法將測試該線程是否為守護線程。值得一提的是,當你在一個守護線程中產生了其他線程,那么這些新產生的線程不用設置Daemon屬性,都將是守護線程,用戶線程同樣。
| import java.io.IOException; /** * 守護線程在沒有用戶線程可服務時自動離開 * @author 五斗米 * @blog http://blog.csdn.net/mq612 */ public class TestMain4 extends Thread { public TestMain4() { } /** * 線程的run方法,它將和其他線程同時運行 */ public void run() { for(int i = 1; i <= 100; i++){ try { Thread.sleep(100); } catch (InterruptedException ex) { ex.printStackTrace(); } System.out.println(i); } } public static void main(String [] args){ TestMain4 test = new TestMain4(); test.setDaemon(true); test.start(); System.out.println("isDaemon = " + test.isDaemon()); try { System.in.read(); // 接受輸入,使程序在此停頓,一旦接收到用戶輸入,main線程結束,守護線程自動結束 } catch (IOException ex) { ex.printStackTrace(); } } } |
===============
http://liujinpan75.iteye.com/blog/653337
所謂守護線程就是運行在程序后臺的線程,程序的主線程Main(比方java程序一開始啟動時創建的那個線程)不會是守護線程??
2.Daemon thread在Java里面的定義是,如果虛擬機中只有Daemon thread 在運行,則虛擬機退出。?
? 虛擬機中可能會同時有很多個線程在運行,只有當所有的非守護線程都結束的時候,虛擬機的進程才會結束,不管在運行的線程是不是main()線程。
3.Main主線程結束了(Non-daemon thread),如果此時正在運行的其他threads是daemon threads,JVM會使得這個threads停止,JVM也停下
? 如果此時正在運行的其他threads有Non-daemon threads,那么必須等所有的Non daemon線程結束了,JVM才會停下來
4.總之,必須等所有的Non-daemon線程都運行結束了,只剩下daemon的時候,JVM才會停下來,注意Main主程序是Non-daemon 線程
? 默認產生的線程全部是Non-daemon線程
class?? A?? implements?? Runnable{?
????????? public?? void?? run(){?
????????????????? for(;;){?
????????????????????????? System.out.println("Thread?? A?? run");?
????????????????? }?
????????? }?
??
????????? public?? static?? void?? main(String[]?? args){?
????????????????? System.out.println("Thread?? main?? started!");?
????????????????? try{?
????????????????????????? (new?? Thread(new?? A())).start();?
????????????????? }?? catch?? (Exception?? e){?
????????????????? }?
????????????????? System.out.println("Thread?? main?? ended!");?
????????? }?
? };?
? 會一直跑下去,因為main進程結束了,但?? A?? 進程還沒有結束,虛擬機不能退出,?
??
? class?? A?? implements?? Runnable{?
????????? public?? void?? run(){?
????????????????? for(;;){?
????????????????????????? System.out.println("Thread?? A?? run");?
????????????????? }?
????????? }?
??
????????? public?? static?? void?? main(String[]?? args){?
????????????????? System.out.println("Thread?? main?? started!");?
????????????????? try{?
????????????????????????? Thread?? a?? =?? new?? Thread(new?? A());?
????????????????????????? a.setDaemon(true);?
????????????????????????? a.start();?
????????????????? }?? catch(Exception?? e){?
????????????????? }?
????????????????? System.out.println("Thread?? main?? ended!");?
????????? }?
? };?
??
? main?? 線程一退出,虛擬機就退出了,因為剩下在跑的?? a?? 線程是守護線程,虛擬機不管它的死活的,直接退出了。
==============
http://www.linuxidc.com/Linux/2012-04/58858.htm
Java將線程分為User線程和Daemon線程兩種。通常Daemon線程用來為User線程提供某些服務。程序的main()方法線程是一個User進程。User進程創建的進程為User進程。當所有的User線程結束后,JVM才會結束。
通過在一個線程對象上調用setDaemon(true),可以將user線程創建的線程明確地設置成Daemon線程。例如,時鐘處理線程、idle線程、垃圾回收線程、屏幕更新線程等,都是Daemon線程。通常新創建的線程會從創建它的進程哪里繼承daemon狀態,除非明確地在線程對象上調用setDaemon方法來改變daemon狀態。
需要注意的是,setDaemon()方法必須在調用線程的start()方法之前調用。一旦一個線程開始執行(如,調用了start()方法),它的daemon狀態不能再修改。通過方法isDaemon()可以知道一個線程是否Daemon線程。
通過執行下面的代碼,可以很清楚地說明daemon的作用。當設置線程t為Daemon線程時,只要User線程(main線程)一結束,程序立即退出,也就是說Daemon線程沒有時間從10數到1。但是,如果將線程t設成非daemon,即User線程,則該線程可以完成自己的工作(從10數到1)。
1.import static java.util.concurrent.TimeUnit.*;?
2.public class DaemonTest {?
2.??? public static void main(String[] args) throws InterruptedException {? 3.??????? Runnable r = new Runnable() {? 4.??????????? public void run() {? 5.??????????????? for (int time = 10; time > 0; --time) {? 6.??????????????????? System.out.println("Time #" + time);? 7.??????????????????? try {? 8.??????????????????????? SECONDS.sleep(2);? 9.??????????????????? } catch (InterruptedException e) {? 10.??????????????????????? e.printStackTrace();?
11.??????????????????? }?
12.??????????????? }?
13.??????????? }?
14.??????? };?
15.?????????
16.??????? Thread t = new Thread(r);? 17.??????? t.setDaemon(true);? // try to set this to "false" and see what happens?? 18.??????? t.start();?
19.?????????
20.??????? System.out.println("Main thread waiting...");? 21.??????? SECONDS.sleep(6);? 22.??????? System.out.println("Main thread exited.");? 23.??? }?
24.}?
?t為Daemon線程的輸出:
Time #10
Time #9
Time #8
Main thread exited.
Time #7
?t為User線程的輸出:
Main thread waiting...
Time #10
Time #9
Time #8
Main thread exited.
Time #7
Time #6
Time #5
Time #4
Time #3
Time #2
Time #1
本篇文章來源于 Linux公社網站(www.linuxidc.com)? 原文鏈接:http://www.linuxidc.com/Linux/2012-04/58858.htm
========http://javarevisited.blogspot.com/2012/03/what-is-daemon-thread-in-java-and.html
Friday, March 16, 2012
What is Daemon thread in Java and Difference to Non daemon thread - Tutorial Example
Daemon thread in Java are those thread which runs in background and mostly created by JVM for performing background task like Garbage collection and other house keeping tasks. Difference between Daemon and Non Daemon(User Threads) ?is also an interesting multi-threading interview question, which asked mostly on fresher level java interviews. In one line main difference between daemon thread and user thread is that as soon as all user thread finish execuction java program or JVM terminates itself, JVM doesn't wait for daemon thread to finish there execution. As soon as last non daemon thread finished JVM terminates no matter how many Daemon thread exists or running inside JVM. In this java thread tutorial we will see example of Daemon thread in Java and some more differences between Daemon and non daemon threads.Important points about Daemon threads in Java
1. Any thread created by main thread, which runs main method in Java is by default non daemon because Thread inherits its daemon nature from the Thread which creates it i.e. parent Thread and since main thread is a non daemon thread, any other thread created from it will remain non-daemon until explicitly made daemon by calling setDaemon(true).2. Thread.setDaemon(true) makes a Thread daemon but it can only be called before starting Thread in Java. It will throw IllegalThreadStateException if corresponding Thread is already started and running.
3. Daemon Threads are suitable for doing background jobs like housekeeping, Though I have yet to use it for any practical purpose in application code. let us know if you have used daemon thread in your java application for any practical purpose.
Difference between Daemon and Non Daemon thread in Java
here are couple of differences between daemon and user thread in Java:1) JVM doesn't wait for any daemon thread to finish before existing.
2) Daemon Thread are treated differently than User Thread when JVM terminates, finally blocks are not called, Stacks are not unwounded and JVM just exits.
Daemon Thread Example in Java
Here is a code example of daemon thread in java. we make a user thread daemon by calling setDaemon(true) and every time you run you will see variable number of print statement related to "daemon thread is running" you will never see print statement written in finally block because finally will not be called.public class DaemonThreadExample {
? ? public static void main(String args[]){
? ?
? ? ? ?Thread daemonThread = new Thread(new Runnable(){
? ? ? ? ? ? @Override
? ? ? ? ? ?public void run(){
? ? ? ? ? ? ? ?try{
? ? ? ? ? ? ? ?while(true){
? ? ? ? ? ? ? ? ? ?System.out.println("Daemon thread is running");
? ? ? ? ? ? ? ?}
? ? ? ? ? ? ? ? ?
? ? ? ? ? ? ? ?}catch(Exception e){
? ? ? ? ? ? ? ? ?
? ? ? ? ? ? ? ?}finally{
? ? ? ? ? ? ? ? ? ?System.out.println("Daemon Thread exiting"); //never called
? ? ? ? ? ? ? ?}
? ? ? ? ? ?}
? ? ? ?}, "Daemon-Thread");
? ? ?
? ? ? ?daemonThread.setDaemon(true); //making this thread daemon
? ? ? ?daemonThread.start();
? ? ?
? ? ?
}
Output: Daemon thread is running Daemon thread is running Daemon thread is running Daemon thread is running Daemon thread is running Daemon thread is running Daemon thread is running Daemon thread is running
That’s all on What is Daemon Thread in Java and difference between Deaemon and non deamon thread in Java with code example of Deamon thread in Java. JVM also uses deamon thread for Garbage collection.
Other Java tutorial on Threads you may like How to Solve Producer Consumer Problem in Java How to Stop Thread in Java Why wait and notify methods are declared in Object Class? Difference between Runnable and Thread in java Why wait and notify needs to called from Synchronized Context?
Difference between invokeAndWait and InvokeLater in java Swing. Difference between wait and sleep in Java Difference between ConcurrentHashMap and Hashtable in Java What is Race condition in java and how to deal with them How to avoid deadlock in Java with code example How to find if a thread holds lock in Java
Read more: http://javarevisited.blogspot.com/2012/03/what-is-daemon-thread-in-java-and.html#ixzz1t6oIGpg0
?
總結
以上是生活随笔為你收集整理的Java线程之守护线程(Daemon) .的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: oracle中实现continue,br
- 下一篇: spring 配置jdbc/hibern