Difference between JAVA daemon thread and user thread

Source: Internet
Author: User

Difference between JAVA daemon thread and user thread

 

public class DaemonTest {    public static void main(String[] args) {        new WorkerThread().start();        try {            Thread.sleep(7500);        } catch (InterruptedException e) {}        System.out.println("Main Thread ending") ;    }}class WorkerThread extends Thread {    public WorkerThread() {        setDaemon(true) ;   // When false, (i.e. when it's a user thread),                // the Worker thread continues to run.                // When true, (i.e. when it's a daemon thread),                // the Worker thread terminates when the main                 // thread terminates.    }    public void run() {        int count=0 ;        while (true) {            System.out.println("Hello from Worker "+count++) ;            try {                sleep(5000);            } catch (InterruptedException e) {}        }    }}

Easy to understand: the daemon does not prevent JVM shutdown. When a user runs a thread, the JVM cannot be disabled. When no user thread is running, it doesn't matter if there is a daemon thread. JVM will shut down.

 

Example of a daemon application: java garbage collection. When no thread is running, no garbage is generated, and the garbage collection does not function. JVM can be disabled.

Background of the daemon thread application: Background threads (for example, threads that can collect certain system states, threads that send emails, and other things that do not want to affect JVM)

 

Related Article

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.