1.java threads fall into two categories, daemon and non-daemon
2. A daemon is a thread that provides a generic service in the background when the program is running. For example, a GC thread is a very competent daemon, and this thread is not an integral part of the program. Therefore, when all non-daemon threads end, the program ends and kills all the daemons in the process. Conversely, if any non-daemon thread is still running, the program will not terminate.
3. There is little difference between the user thread and the daemon thread, and the only difference is that the virtual machine is leaving: If the user thread has all exited, only the daemon thread exists and the virtual machine exits. Because there is no guardian, the daemon thread has no work to do, and there is no need to continue running the program.
4. Convert a thread to a daemon thread: Invoke the Setdaemon (true) method of the thread object to implement it. But you need to pay attention to a few things:
~thread.setdaemon (true); it must be set before Thread.Start (), otherwise a illegalthreadstateexception exception will be thrown, and you cannot set the thread to be a daemon when thread runs.
~ The new thread produced in the daemon thread is also daemon.
~ a daemon thread should never access an intrinsic resource, such as a file or database, because it interrupts at any time, even in the middle of an operation.
Package com.sxt.thread;
Import Java.io.File;
Import java.io.FileNotFoundException;
Import Java.io.FileOutputStream;
Import java.io.IOException;
/**
* @author JT
* 2015-12-6 4:09:28
*
*/
public class Testrunnable implements runnable{
/* (Non-javadoc)
* @see Java.lang.runnable#run ()
*/
@Override
public void Run () {
try {
Thread.Sleep (1000);//daemon Blocking one second execution
File f=new filename ("e://deamon.txt");//Create Files
FileOutputStream os=new FileOutputStream (f);//Create a text-price output stream
Os.write ("Deamon". GetBytes ());//program output data to file (write data to file)
catch (Interruptedexception e) {
E.printstacktrace ();
catch (FileNotFoundException e) {
E.printstacktrace ();
catch (IOException e) {
E.printstacktrace ();
}
}
}
Package com.sxt.thread;
/**
* @author JT
* 2015-12-6 4:19:39
*
*/
public class Testdemon {
/**
* @param args
*/
public static void Main (string[] args) {
Runnable rb=new testrunnable ();
Thread Th=new thread (RB);
Th.setdaemon (TRUE);//Set as Daemon
Th.start ();
}
}
Run Result: There is no "daemon" string in file Daemon.txt.
The file Daemon.txt can be written to the daemon string if Th.setdaemon (true)//is set as the code for the daemon thread to comment out.