For thread, there are only two methods to say, one is Setdaemon (false|true) and the other is join (). First of all, the Guardian thread, what is this thing used for? For Java applications We all know that the main method is the portal, its operation represents the main thread began to work, we also know that the JVM has a garbage collector exists so that we can rest assured that the main gallop, but the story behind this is garbage collection thread as the guardian of the main thread silently pay. Very like that what ah, hehe. Heinous is main this beast behind in fact there are several guardian threads silently pay! Of course, if you just want to put the Guardian thread than to do a woman, not a guardian thread than to do a man, then a man can have a number of silently pay women. Java in the design of the default of this realistic society is not able to realize the reality, and mandatory provisions if the man is not, the virtual world over, it seems that the capitalist society under the creation of the child is the lifeblood of feudal society ah! Yes, the implementation inside the JVM is that if the running program is left with only a daemon, the program will terminate and end directly. So the daemon thread exists as a helper thread, and the main function is to provide support for counting and so on. Here is a small example to illustrate:
Java code
/**
* User: yanxuxin
* Date: Dec 10, 2009
* Time: 7:16:55 PM
*/
public class DaemonSample {
public static void main(String[] args) throws Exception{
DaemonThread t = new DaemonThread();
t.setDaemon(true);//this is set t thread as a daemon thread.
t.start();
Thread.sleep(2000);
System.out.println("main thread exit.");
}
}
class DaemonThread extends Thread {
@Override
public void run() {
for(int i = 0; i < 10; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("i=" + i);
}
}
}
The result of this example is that the main main thread sleeps after two seconds to say good-bye, while the child thread counts the count in two seconds and then says good-bye. Of course it's very reluctant, because it wants to count for 10 seconds, but no chance. Comment out T.setdaemonthread (true) you'll see the main thread say good-bye, but the child threads happily finish she used goodbye. This is the role of the Guardian thread, all with a non-daemon thread-oriented! Very spoony ah, haha.