/**
* 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