Daemon thread (background thread) and non-daemon thread (user thread, foreground thread)

Source: Internet
Author: User

After the current thread ends, the JVM will kill the background thread directly, and the background thread will not execute the contents of the finally code block

public class DemoThread implements Runnable {@Overridepublic void Run () {//TODO auto-generated method Stubtry {thread.cur Rentthread (). Sleep (1000); System.out.println ("I am a non-guardian thread");} catch (Interruptedexception e) {//TODO auto-generated catch Blocke.printstacktrace ();};}}

  

public class Main {public static void main (string[] args) {ThreadStart ();} public static void ThreadStart () {DemoThread dt = new DemoThread (); Thread thread = new thread (dt); Thread.setdaemon (true); Thread.Start ();}}

1, when the direct start, will not print out the content

2. When Thread.setdaemon (true) is removed, "I am a non-Guardian thread" is printed.

Cause analysis: When the thread is set as the daemon thread, the main thread is the foreground thread, and after execution it ends directly, the JVM directly kill the thread of the daemon thread, the content of this daemon thread will not continue to execute; When the line is removed, thread defaults to the foreground thread. The JVM waits until all foreground threads have finished executing, and the thread thread prints out the content

Daemon thread (background thread) and non-daemon thread (user thread, foreground thread)

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.