I suddenly saw the usage of thread. setdaemon in a program. After learning, I will understand:
1. setdaemon must be used before the start method is called.
2. threads are divided into user threads and daemon processes. setdaemon sets the thread as a background process.
3. If the JVM is a background process, the current JVM will exit. (As a result, all the data is scattered, including the background threads)
4. After the main thread ends,
4.1 The user thread will continue to run
4.2 if no user thread exists and all are background processes, the JVM ends.
Sample:
[Java]
View plaincopy
- Package A. B. C;
- Import java. Io. ioexception;
- Public class testthread extends thread {
- Public testthread (){
- }
- /***//**
- * The run method of the thread, which runs together with other threads
- */
- 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 ){
- Testthread test = new testthread ();
- // If no daemon is set, the thread will output 100 before it ends.
- Test. setdaemon (true );
- Test. start ();
- System. out. println ("isDaemon =" + test. isDaemon ());
- Try {
- System. in. read (); // receives the input so that the program pauses. Once the user input is received, the main thread ends and the daemon thread ends automatically.
- } Catch (IOException ex ){
- Ex. printStackTrace ();
- }
- }
- }