004 Background Threads

Source: Internet
Author: User

One. Background thread

A thread is a special thread that is designated to execute in the background when it is created.


[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.


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

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.