Java multithreading Summary 2: Background threads (daemon threads)

Source: Internet
Author: User

The so-called background thread refersProgramA General Service thread is provided in the background during running, and this thread is not an indispensable part of the program. Therefore, when all non-Background threads end, the program will terminate and all background threads will be killed. Conversely, the program will not be terminated as long as any non-Background thread (User thread) is still running.The background thread terminates the run method without executing the finally clause..The subthread created by the background thread is also a background thread.

The following is an example of a background thread:

Package demo. thread; import Java. util. concurrent. timeunit; public class daemondemo implements runnable {@ overridepublic void run () {try {While (true) {thread. sleep (1, 1000); system. out. println ("#" + thread. currentthread (). getname () ;}} catch (interruptedexception e) {e. printstacktrace ();} finally {// The background thread does not execute the finally Clause system. out. println ("finally") ;}} public static void main (string [] ARGs) {for (INT I = 0; I <10; I ++) {thread daemon = new thread (New daemondemo (); // It must be set to the background thread daemon before start. setdaemon (true); daemon. start ();} system. out. println ("all daemons started"); try {timeunit. milliseconds. sleep (1000);} catch (interruptedexception e) {// todo auto-generated catch blocke. printstacktrace ();}}}


 

Running result:

All daemons started
# Thread-2
# Thread-3
# Thread-1
# Thread-0
# Thread-9
# Thread-6
# Thread-8
# Thread-5
# Thread-7
# Thread-4

Analysis: From the results, we can see that the ten sub-threads do not print wireless loops. Instead, after the main thread (main () exits, the JVM forces to close all background threads. There is no desired confirmation form, for example, the finally clause is not executed.

 

 

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.