Thread. setdaemon

Source: Internet
Author: User

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
  1. Package A. B. C;
  2. Import java. Io. ioexception;
  3. Public class testthread extends thread {
  4. Public testthread (){
  5. }
  6. /***//**
  7. * The run method of the thread, which runs together with other threads
  8. */
  9. Public void run (){
  10. For (INT I = 1; I <= 100; I ++ ){
  11. Try {
  12. Thread. Sleep (100 );
  13. } Catch (interruptedexception ex ){
  14. Ex. printstacktrace ();
  15. }
  16. System. Out. println (I );
  17. }
  18. }
  19. Public static void main (string [] ARGs ){
  20. Testthread test = new testthread ();
  21. // If no daemon is set, the thread will output 100 before it ends.
  22. Test. setdaemon (true );
  23. Test. start ();
  24. System. out. println ("isDaemon =" + test. isDaemon ());
  25. Try {
  26. 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.
  27. } Catch (IOException ex ){
  28. Ex. printStackTrace ();
  29. }
  30. }
  31. }

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.