One. Background thread
A thread is a special thread that is designated to execute in the background when it is created.
Attention:
[1] The background thread needs to be specified before starting.
[2]daemnon has a low priority, meaning it has fewer chances to run.]
[3] The life cycle of a background thread relies on the life cycle of its parent thread, that is, if there is no non-background thread,
Then the background thread ends automatically.
Let's look at an example:
Public classDaemonthread { Public Static voidMain (string[] args) {//create a thread that will constantly print its own nameThread thread =NewThread () {@Override Public voidrun () { while(true) {System. out. println (Thread.CurrentThread (). GetName ()); Try{TimeUnit.SECONDS.sleep (1); } Catch(interruptedexception e) {e.printstacktrace (); } } } }; //Thread.setdaemon (true);Thread.Start (); }}
In the above we create a thread, which is a non-background thread, so its life cycle is not related to other threads.
So now we're running and we're going to print the name of the thread constantly.
When we open the comment:
We find that threads do not constantly print their own names, but instead actively end their life cycles at the end of the main thread.
Summarize:
Background thread We can think of as a subordinate thread whose life cycle depends on the life cycle of its parent thread.
For example, there is an application that requires a sub-thread to constantly send messages to the other server to confirm that the other is offline.
Then we can use a background thread to accomplish this task.
We use a background thread to do this, and if the main thread ends, then we don't need to send the heartbeat package again.
004 Background Threads