Java foreground thread and background thread
Last blog in the Main () method, after creating and starting four new threads, the code in the main () method completes, at which point the method ends and the main thread ends.
The results of the program can be seen, although the main thread ended, but the entire Java program has not ended, still executing the ticket sales code
For Java programs, as long as there is a foreground thread running, this process will not end, if a process, only the background thread is running, this process will end the foreground thread and background thread
foreground thread, background thread is a relative concept
The newly created thread, which defaults to the foreground thread
If a thread object calls the Setdaemon (true) statement before it starts, the thread becomes a background thread
Example, Example06.java
Create Damonthread class, implement Runnable interface
class Damonthread implements runnable{
//Implementation Interface run () method public
void run () { While
(true) {
System.out.println (Thread.CurrentThread (). GetName () + '---is running. ');
}} public class example06{public
static void Main (string[] args) {
System.out.println ("Main thread is a background thread.") "+thread.currentthread (). Isdaemon ());
Create a Damonthread object dt
//create thread T, share dt resource
Damonthread dt=new damonthread ();
Thread t=new thread (dt, "background thread");
System.out.println ("T-thread default is background thread.) "+t.isdaemon ());
The thread T, set to the background thread
//Call Start () method, opens the thread T
T.setdaemon (TRUE);
T.start ();
for (int i=0;i<10;i++) {
System.out.println (i);
}
}
}
Compile run
Demonstrates the process of ending a background thread
When the thread T is turned on, the print statement in the dead loop is executed, and after we set the thread T as the background thread, the JVM notifies the background thread after the current thread dies.
Since the background thread takes a certain amount of time from the receiving instruction to the response, the background thread also ends after printing several times behind the background thread-is running statement
Therefore, when the background thread is running, the process ends setting up the background thread
To set a thread as a background thread, you must before the thread starts
In other words, the Setdaemon () method must be called before the start () method, otherwise, a Illegaltreadstateexception exception is thrown