The daemon thread uses less, but is not useless, for example, the JVM's garbage collection, memory management, and other threads are daemon threads. There is in doing database application, the use of the database connection pool, the connection pool itself also contains a lot of background threads, monitoring the number of connections, timeout time, state and so on.
Detailed description of the Setdaemon method:
Public final void Setdaemon marks the thread as a daemon or user thread. When a running thread is a daemon, the Java virtual machine exits.
The method must be called before the thread is started.
The method first invokes the CheckAccess method of the thread with no arguments. This may throw SecurityException (in the current thread).
Parameters:
On-if true, marks the thread as a daemon.
Thrown:
Illegalthreadstateexception-If the thread is active.
SecurityException-If the current thread cannot modify the thread.
See also:
Isdaemon (), CheckAccess ()
/**
* java thread: Scheduling of threads-Daemon Threads
*
* @author leizhimin
*/
public class Test {
Public stat IC void Main (string[] args) {
Thread t1 = new Mycommon ();
Thread t2 = new Thread (new Mydaemon ());
T2.setdaemon (TRUE);//set to Daemon
T2.start ();
T1.start ();
}
}
Class Mycommon extends Thread {
public void run () {
for (int i = 0; I < 5; i++) {
System.out.println ("Thread 1" + i + "secondary execution!") ");
try {
Thread.Sleep (7);
catch (Interruptedexception e) {
E.printstacktrace ();
}
}
}
Class Mydaemon implements Runnable {
public void run () { for (long i = 0; i < 9999999L; i++) {
System.out.println ("Background line Cheng Di" + i +) secondary execution! ");
try {
Thread.Sleep (7);
catch (Interruptedexception e) {
E.printstacktrace ();
}
}
}
后台线程第0次执行!
线程1第0次执行!
线程1第1次执行!
后台线程第1次执行!
后台线程第2次执行!
线程1第2次执行!
线程1第3次执行!
后台线程第3次执行!
线程1第4次执行!
后台线程第4次执行!
后台线程第5次执行!
后台线程第6次执行!
后台线程第7次执行!
Process finished with exit code 0
From the above results you can see that:
The foreground thread is guaranteed to execute, and the background thread exits before it has finished executing.
In fact: The standard for a JRE to determine whether a program is finished is to have all the front line Cheng completed, regardless of the background thread status, so be sure to pay attention to this problem when using the back seat.
Source: http://lavasoft.blog.51cto.com/62575/221845