Java Daemon Thread

Source: Internet
Author: User

/**
* A background thread is also called a daemon thread, usually a thread that runs in order to assist other threads, '
* The background thread does not prevent the program from terminating,
* As long as there is a foreground thread executing in a program, this background thread will not terminate.
* Conversely, if all foreground threads have ended, the process will end, whether or not there are background threads executing.
* If you call the Setdeamon (True) method before starting (calling the start () method) on a thread object, the thread becomes a background thread.
* Create an infinite loop background thread and verify that the foreground thread ends after it also ends
*/

Package Com.starain.threaddemo;

public class Daemonthread {
public static void Main (string[] args) {
Frontthreadtester T1 = new Frontthreadtester (20);
Thread thread1 = new Thread (T1, "Thread1");
Daemonthreadtester thread2 = new Daemonthreadtester ("Daemon");
Thread1.start ();
Thread2.setdaemon (TRUE);
Thread2.start ();
}
}

Class Frontthreadtester implements runnable{//implement Runnable method to create a thread
private int number;
public Frontthreadtester (int number) {
This.number = number;
}
public void Run () {
for (int i = 1; I <= number; i++) {
System.out.println ("Foreground thread" +thread.currentthread (). GetName () + "executing section +i+");
}
}
}
Class Daemonthreadtester extends thread{//extension (inheritance) thread class creating threads
private String name;
Public Daemonthreadtester (String name) {
THIS.name = name;
}
public void Run () {
Super.run ();
while (true) {
try {
Thread.Sleep (1);
System.out.println (name+ "is running ...");
} catch (Interruptedexception e) {
E.printstacktrace ();
}
}
}
}

Java Daemon 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.