Home > Java > javaTutorial > What is the difference between daemon threads and user threads in Java?

What is the difference between daemon threads and user threads in Java?

王林
Release: 2023-04-23 14:49:07
forward
1855 people have browsed it

Different definitions

User thread: The threads used in daily life are all user threads.

Daemon thread: a thread used to serve user threads, such as garbage collection threads.

Differences in functions

1. The difference between daemon threads and user threads is mainly that the Java virtual machine survives.

2. User thread: When any user thread has not ended, the Java virtual machine will not end. Daemon thread: If only the daemon thread is left and has not ended, the Java virtual machine ends.

Instance

Start the daemon thread in the main thread.

package com.thread.model.threads;
 
 
/**
 * Hello world!
 *
 */
public class ThreadClass 
{
    public static void main( String[] args )
    {
        Thread thread = new Thread(new Runnable() {
 
 
public void run() {
while(true) {
try {
System.out.println("守护线程心跳一次");
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
       
        });
        
        thread.setDaemon(true);//将该线程设置为守护线程
        
        thread.start();
        
        try {
Thread.sleep(10000);
Thread currentthread = Thread.currentThread();
System.out.println("主线程"+currentthread.getName()+"退出!");
} catch (InterruptedException e) {
e.printStackTrace();
}
    }
 
}
Copy after login

The above is the detailed content of What is the difference between daemon threads and user threads in Java?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template