004 Background thread

1. Background thread

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

Notice: 

  [1] Background threads need to be specified before starting.

  [2] The priority of daemnon is very low, which means that it has less chance of running.

  [3] The lifetime of a background thread depends on the lifetime of its parent thread, that is, if there are no non-background threads,

    Then the background thread ends automatically.

Let's see an example:

  

public class DaemonThread {

    public  static  void main(String[] args) {
         // Create a thread, this thread will keep printing its own name 
        Thread thread = new Thread() {
            @Override
            public void run() {
                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 created a thread, this thread is a non-background thread, so its life cycle has nothing to do with other threads.

Therefore, now we will keep printing the name of the thread when we run it.

When we open annotations:

  We found that now the thread does not continuously print its own name, but actively ends its life cycle when the main thread terminates.

 

Summarize: 

  We can think of a background thread as a subordinate thread whose life cycle depends on the life cycle of its parent thread.

  For example, there is an application now, which needs a child thread to continuously send messages to the other party's server to confirm whether the other party is offline.

  Then we can use a background thread to complete this task.

  We use a background thread to complete this task. If the main thread terminates, then we don't need to send heartbeat packets again.

  

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325039979&siteId=291194637