There are two types of threads in Java: User thread, Daemon thread (daemon thread)
The daemon thread is not only available inside the virtual machine, but the user can also set the daemon itself when writing the program. The following method is used to set the daemon thread.
1 Thread daemontread = new Thread (); 2 3 set Daemonthread as the daemon thread, default false (non-daemon thread) 4 Daemonthread.setdaemon (true 5 6 Verifies whether the current thread is a daemon thread, returns true as a daemon 7 Daemonthread.isdaemon ();
There are a few points to note:
(1) Thread.setdaemon (true) must be set before Thread.Start () or run out of a illegalthreadstateexception exception. You cannot set a running regular thread as a daemon thread.
(2) The new thread generated in the daemon thread is also daemon.
(3) Do not assume that all applications can be assigned to daemon for service, such as read-write operations or computational logic.
For the 3rd, let's look at an example
1 Public classMyThreadextendsThread {2 @Override3 Public voidrun () {4 Try {5Thread.Sleep (1000);//The daemon thread is blocked for 1 seconds before running6FileOutputStream FIS =NewFileOutputStream (NewFile ("E://test.txt"));7Fis.write ("Test a nonrm cmd". GetBytes ());8}Catch(FileNotFoundException e) {9 e.printstacktrace ();Ten}Catch(IOException e) { One e.printstacktrace (); A}Catch(interruptedexception e) { - e.printstacktrace (); - } the } -}
1 Public class Run {2 Public Static void throws interruptedexception {3 New MyThread (); 4 Mythread.setdaemon (true); 5 Mythread.start (); 6 }7 }
You can see that the file writes correctly when the thread is not set as the daemon thread
But when it is set as a daemon, the content is not written in.
We know that static variables are classloader levels, and if the Web application stops, these static variables are also purged from the JVM. But the thread is at the JVM level, and if you start a thread in a web app, the thread's life cycle does not stay in sync with the Web application. In other words, even if you stop the Web app, the thread is still active . because of this very obscure problem, many experienced developers are not quite in favor of launching threads in Web applications.
If we use the JDK timer manually (Quartz scheduler), start the timer when the Web container starts, and when the Web container is closed, the task in the timer will continue to run unless you manually close the timer !
Understanding of daemon Threads in Java Multi-threading