One, background thread (Guardian thread)
Learn a thing, the most important thing is, why use it?
A background thread differs from a normal thread, and a normal thread can be called a user thread, completing only the tasks the user wants to accomplish, and not providing a public service. And sometimes, we want to write a program that provides a public service that ensures that all users are responding to requests for that thread.
Take a closer look at the definition of a background thread: a thread that provides a generic service in the background while the program is running, and this thread is not an integral part of the program.
Second, the implementation of background threads
1. We first define the task and the response thread
Define tasks: Thread.yield (); Let threads pause for a while
class Implements runnable{ publicvoid run () { while(true) Thread.yield (); }}
Set a thread that has a property thread[] t, which is used to hold child threads
classDaemonImplementsrunnable{//Create many sub-threads under this task Privatethread[] t =NewThread[10]; Public voidrun () {//Populate threads for thread pool and start all threads for(inti = 0; i < t.length; i++) {T[i]=NewThread (Newdaemonspawn ()); T[i].start (); System.out.println ("Daemonspawn" +i+ "started,"); } for(inti = 0; i < t.length; i++) {System.out.println ("t[" +i+ "].isdaemon () =" +t[i].isdaemon () + ","); } /** Daemon enters the wireless loop and calls the yield method in the loop to give control to other processes*/ while(true) Thread.yield (); }}
Defines a thread that is set as a background thread
public static void Main (string[] args) throws interruptedexception{ /* * Daemon is set to a background thread, all of its child threads are also naturally background threads */ Th Read D = new Thread (new Daemon ()); d.setdaemon ( true D.start (); System.out.println ( "d.isdaemon () =" +d.isdaemon () + "," 1); }
At this point, the background thread is defined and running. Output Result:
daemonspawn 0started, Daemonspawn 1started, Daemonspawn 2started, Daemonspawn 3started, Daemonspawn 4started, Daemonspawn 5started, Daemonspawn 6started, Daemonspawn 7started, Daemonspawn 8started, Daemonspawn 9started, t[0].isdaemon () =true, t[1].isdaemon () =true, t[2].isdaemon () =true, t[3].isdaemon () =true, t[4].isdaemon () =true, t[5].isdaemon () =true, t[6].isdaemon () =true, t[7].isdaemon () =true, t[8].isdaemon () =true, t[9].isdaemon () =true, D.isdaemon ()+true,
2. One point to point out: when all "non-background Threads" end, the program terminates and kills all the background threads in the process: main is a non-background thread
First of all, how to prove that main is a non-background thread, or the above program
Secondly, how to prove that the background thread will be killed after the non-background thread exits?
Public classTaskdaemonImplementsrunnable{@Override Public voidrun () {Try{ while(true) {TimeUnit.MILLISECONDS.sleep (100); System.out.println (Thread.CurrentThread ()+" "+ This); } }Catch(interruptedexception e) {System.out.println ("Sleep () interrupted"); } } Public Static voidMain (string[] args)throwsinterruptedexception{/** You can see the results of the program to understand the background thread * created 9 threads, are declared as background threads, and then start them, before the end of the non-background thread, the background thread will be called by the thread caller * Main is a non-background thread, for loop After the end, "All daemons started" proves that main is about to end, but you let it sleep for a while to ensure that main does not quit * so that the background thread will run, and then have the results of the subsequent printing*/ for(inti = 0; I < 10; i++){ //A background thread is essentially a thread that creates the thread through a taskThread daemon =NewThread (NewTaskdaemon ()); //to declare the created thread as a background thread, you must set it to true before startingDaemon.setdaemon (true); Daemon.start (); } System.out.println ("All daemons started"); TimeUnit.MILLISECONDS.sleep (175); } }
3. Use the Isdaemon () method to determine whether a thread is a background thread
Any thread created by a background thread will be automatically set as a background thread, for example: Daemons.
4. The background thread terminates its run () method without executing the finally sentence, for example: daemonsdontrunfinally
class adaemon implements runnable{@Override public void run () { try {System.out.println ( "Starting Adaemon" ); TimeUnit.SECONDS.sleep ( 1); catch (Interruptedexception e) {syste M.out.println ( "Exiting via interruptedexception" ); finally {System.out.println ( " Thie should always run? " ); } }}
Public Static void Main (string[] args) { // when the last non-background thread terminates, the background thread will "suddenly" terminate // so once main exits, The JVM shuts down all background processes immediately, without any confirmation form you want to appear in new Thread (new Adaemon ()); // If you comment out the following statement, finally will execute T.setdaemon (true); T.start ();}
You can see the output, and finally the result is not executed
Third, custom background thread factory
1. Customizing the background Thread Factory
Public class Implements threadfactory{ public thread Newthread (Runnable r) { new Thread (r); T.setdaemon (true); return t; }}
2. Try the factory when creating a thread
/ * * Executors.newcachedthreadpool (); method is used to accept a Threadfactory object, and this object will be used to create a new thread * So, After your facotry has rewritten the Threadfacotry method, to implement his method of creating threads, the default method is to declare the thread as a background thread * /= Executors.newcachedthreadpool (new taskdaemonfactory ()); for (int i = 0; i < i++) { exec.execute (new taskdaemonfromfactory ()); This is a custom task } System.out.println ("Alldaemons started"); TimeUnit.MILLISECONDS.sleep (500);
Iv. Summary
Background thread (daemon)
|--definition: A thread that provides a generic service in the background while the program is running, and this thread is not part of the program
| |--All "non-background Threads" end, the program terminates and kills all background threads in the process: main is a non-background thread
|--declaring and experimenting with background threads
| |--Traditional way: Define a background thread by declaring a thread, manipulating threads
| | |--thread daemon = new Thread (new Taskdaemon ());//Assign a task to a thread also called a declarative thread
| | |--daemon.setdaemon (TRUE);//Set the thread as a background thread
| | |--daemon.start ();//Start background thread
| |--thread Factory is called by Executor: by writing custom threadfactory, you can customize the properties of threads created by executor
| |--1. Implementing the Threadfactory Interface
| |--2. Overriding the Newthread method
| |--public Thread Newthread (Runnable r) {
| |--thread t = new Thread (r);
| |--t.setdaemon (TRUE);
| |--return T;
| |--}
| |--3. Pass the custom taskdaemonfactory to executor, which will use this to generate the corresponding thread and manipulate them
| |--each static Executorservice creation method is overloaded to accept a Threadfactory object that will be used to create a new thread
| |--executorservice exec = Executors.newcachedthreadpool (new taskdaemonfactory ());
| |--4. Pass the task to exec, which will help you perform thread operations
| |--exec.execute (New Taskdaemonfromfactory ());
Note: The above code is from the "Thinking in Java", the summary of the contents are personal understanding, if there are errors please criticize correct, thank you
Java multithreaded--< five > Background thread (daemon)