Parsing of backend thread instances in Java and java backend thread instances

Source: Internet
Author: User

Parsing of backend thread instances in Java and java backend thread instances

This article focuses on the background thread issues in Java. The details are as follows.

I have never heard of background threads in java before. Generally, JVM (Java Virtual Machine) generally includes two threads: User thread and background thread. The so-called daemon thread refers to a general service thread provided in the background when the program is running, and this thread is not an indispensable part of the program. Therefore, when all non-Background threads end, that is, when the user threads end, the program is terminated. At the same time, all background threads in the process will be killed. Conversely, as long as any non-Background thread is still running, the program will not end. It is better to execute main () as a non-Background thread.

Based on this feature, when all user threads in the virtual machine exit and the daemon thread does not have a service object, the JVM exits.

This is already described in the JDK source code.

* Marks this thread as either a {@ linkplain # isDaemon daemon} thread
* Or a user thread. The Java Virtual Machine exits when the only
* Threads running are all daemon threads.

1. Background thread startup conditions:

/* You must call the SetDaemon () method before starting the thread to set this thread as a background thread. * In this program, when we input a string, the Main thread will stop running * then there is no user thread in the program that can run. So the background thread will be stopped * JVM will be stopped. Interested readers can try it by themselves */public class DaemonRunner implements Runnable {@ Override public void run () {while (true) {for (int I = 0; I <3; I ++) {System. out. println ("daemthread" + I) ;}} public static void main (String [] args) {Thread daemon = new Thread (new DaemonRunner (); daemon. setDaemon (true); daemon. start (); Scanner s = new partition (System. in); String string = s. nextLine (); Runtime. getRuntime (). addShutdownHook (new Thread () {@ Override public void run () {super. run (); System. out. println ("JVM exited"); try {TimeUnit. MILLISECONDS. sleep (50);} catch (InterruptedException e) {e. printStackTrace ();}}});}}

2. All threads started in the background thread belong to the background thread.Although you have not explicitly indicated that they are background threads, they are indeed background threads.

/* You can call the isDaemon () method to determine whether the thread is a background thread. If it is a background thread, * any thread created by it is automatically set to a background thread * in this instance, the Daemon thread is set to the background mode, then many subthreads are derived. These threads are not set to * Background mode, but they are indeed background threads. Then, the Daemon thread enters an infinite loop, the yield Method * is called in the loop to give control to other threads or processes */class Daemon implements Runnable {private Thread [] t = new Thread [10]; @ Override public void run () {for (int I = 0; I <t. length; I ++) {t [I] = new Thread (new DaemonSpawn (); t [I]. start (); System. out. println ("DaemonSpawn" + I + "started") ;}for (int I = 0; I <t. length; I ++) {System. out. println ("t [" + I + "]. isDaemon "+ t [I]. isDaemon ();} while (true) {Thread. yield () ;}} class DaemonSpawn implements Runnable {@ Override public void run () {while (true) {Thread. yield () ;}} public class Daemons {public static void main (String [] args) {Thread d = new Thread (new Daemon (); d. setDaemon (true); d. start (); System. out. println ("d. isDaemon () = "+ d. isDaemon (); try {TimeUnit. SECONDS. sleep (1); // enables the startup background thread to get a certain execution time .} Catch (InterruptedException e) {e. printStackTrace ();}}}

The final execution result is as follows:

D. isDaemon () = true
DaemonSpawn 0 started
DaemonSpawn 1 started
DaemonSpawn 2 started
DaemonSpawn 3 started
DaemonSpawn 4 started
DaemonSpawn 5 started
DaemonSpawn 6 started
DaemonSpawn 7 started
DaemonSpawn 8 started
DaemonSpawn 9 started
T [0]. isDaemontrue
T [1]. isDaemontrue
T [2]. isDaemontrue
T [3]. isDaemontrue
T [4]. isDaemontrue
T [5]. isDaemontrue
T [6]. isDaemontrue
T [7]. isDaemontrue
T [8]. isDaemontrue
T [9]. isDaemontrue

3.Executors.newCachedThreadPool()Method to specify a ThreadFactory object. In this way, we can also
Set the thread to be started as the background thread.

/* In this example, Executors is the static constructor. newCachedThreadPool (new DaemonThreadFactory () * We can pass in a ThreadFactory object, so we can use this method to set the thread we want to start as the background thread * this is worth noting. */Class DaemonThreadFactory implements ThreadFactory {@ Override public Thread newThread (Runnable r) {Thread t = new Thread (r); t. setDaemon (true); return t ;}/ * in this example, in the Main method, the common method in the Main method is called first, "System. out. println ("All dameons started"); "* this statement is printed first. Then, during the sleep of the Main thread, the corresponding background thread will get the execution time, and when the Main thread * stops running, that is, when the Main thread recovers from sleep, the Main linear operation ends. Then, * all background threads will stop. JVM also stops execution. */Public class DaemonFromFactory implements Runnable {@ Override public void run () {try {while (true) {TimeUnit. MILLISECONDS. sleep (1, 100); System. out. println (Thread. currentThread () + "" + this) ;}} catch (InterruptedException e) {System. out. println ("Interrupted") ;}} public static void main (String [] args) {ExecutorService exec = Executors. newCachedThreadPool (new DaemonThreadFactory (); for (int I = 0; I <10; I ++) exec.exe cute (new DaemonFromFactory ();} System. out. println ("All dameons started"); try {TimeUnit. MILLISECONDS. sleep (500);} catch (InterruptedException e) {e. printStackTrace ();}}}

The final output result is:

All dameons started
Thread [Thread-3, 5, main] Concurrency. DaemonFromFactory @ 56214c1
Thread [Thread-2, 5, main] Concurrency. DaemonFromFactory @ 5724147d
Thread [Thread-0, 5, main] Concurrency. DaemonFromFactory @ 144fe080
Thread [Thread-1, 5, main] Concurrency. DaemonFromFactory @ 104fa29e
Thread [Thread-8, 5, main] Concurrency. DaemonFromFactory @ 5b069a7f
Thread [Thread-9, 5, main] Concurrency. DaemonFromFactory @ 1a7288d1
Thread [Thread-7, 5, main] Concurrency. DaemonFromFactory @ 25144c3e
Thread [Thread-4, 5, main] Concurrency. DaemonFromFactory @ 288523d
Thread [Thread-6, 5, main] Concurrency. DaemonFromFactory @ 1edae2a8
Thread [Thread-5, 5, main] Concurrency. DaemonFromFactory @ 626007aa
Thread [Thread-3, 5, main] Concurrency. DaemonFromFactory @ 56214c1
Thread [Thread-2, 5, main] Concurrency. DaemonFromFactory @ 5724147d
Thread [Thread-6, 5, main] Concurrency. DaemonFromFactory @ 1edae2a8
Thread [Thread-5, 5, main] Concurrency. DaemonFromFactory @ 626007aa
Thread [Thread-4, 5, main] Concurrency. DaemonFromFactory @ 288523d
Thread [Thread-9, 5, main] Concurrency. DaemonFromFactory @ 1a7288d1
Thread [Thread-7, 5, main] Concurrency. DaemonFromFactory @ 25144c3e
Thread [Thread-8, 5, main] Concurrency. DaemonFromFactory @ 5b069a7f
Thread [Thread-1, 5, main] Concurrency. DaemonFromFactory @ 104fa29e
Thread [Thread-0, 5, main] Concurrency. DaemonFromFactory @ 144fe080
Thread [Thread-2, 5, main] Concurrency. DaemonFromFactory @ 5724147d
Thread [Thread-3, 5, main] Concurrency. DaemonFromFactory @ 56214c1
Thread [Thread-6, 5, main] Concurrency. DaemonFromFactory @ 1edae2a8
Thread [Thread-1, 5, main] Concurrency. DaemonFromFactory @ 104fa29e
Thread [Thread-0, 5, main] Concurrency. DaemonFromFactory @ 144fe080
Thread [Thread-7, 5, main] Concurrency. DaemonFromFactory @ 25144c3e
Thread [Thread-8, 5, main] Concurrency. DaemonFromFactory @ 5b069a7f
Thread [Thread-5, 5, main] Concurrency. DaemonFromFactory @ 626007aa
Thread [Thread-9, 5, main] Concurrency. DaemonFromFactory @ 1a7288d1
Thread [Thread-4, 5, main] Concurrency. DaemonFromFactory @ 288523d
Thread [Thread-2, 5, main] Concurrency. DaemonFromFactory @ 5724147d
Thread [Thread-3, 5, main] Concurrency. DaemonFromFactory @ 56214c1
Thread [Thread-8, 5, main] Concurrency. DaemonFromFactory @ 5b069a7f
Thread [Thread-7, 5, main] Concurrency. DaemonFromFactory @ 25144c3e
Thread [Thread-4, 5, main] Concurrency. DaemonFromFactory @ 288523d
Thread [Thread-6, 5, main] Concurrency. DaemonFromFactory @ 1edae2a8
Thread [Thread-1, 5, main] Concurrency. DaemonFromFactory @ 104fa29e
Thread [Thread-0, 5, main] Concurrency. DaemonFromFactory @ 144fe080
Thread [Thread-9, 5, main] Concurrency. DaemonFromFactory @ 1a7288d1
Thread [Thread-5, 5, main] Concurrency. DaemonFromFactory @ 626007aa
Thread [Thread-3, 5, main] Concurrency. DaemonFromFactory @ 56214c1
Thread [Thread-2, 5, main] Concurrency. DaemonFromFactory @ 5724147d
Thread [Thread-8, 5, main] Concurrency. DaemonFromFactory @ 5b069a7f

4. First, we should realize that if the user thread suddenly exits, the background thread will terminate the run method without executing the finally clause.

/* When you call this program, you will see that the finally clause will not be executed, but if you comment out the call to setDaemon (), you will see that the * finally clause will be executed. * This behavior is correct. Even if you do not want such behavior, based on the promise given by finally. But this is the case * when the last non-Background thread is terminated, the background thread will suddenly stop. Once main () exits, JVM immediately closes all background * threads. Because you cannot close background threads in an elegant way, they are hardly a good idea. Non-Background Executor is usually a * better way, because all tasks controlled by Executor can be disabled at the same time. */Class ADaemon implements Runnable {@ Override public void run () {System. out. println ("Starting ADaemon"); try {TimeUnit. SECONDS. sleep (1);} catch (InterruptedException e) {System. out. println ("Exiting via InterruptedException");} finally {System. out. println ("This shoshould always run? ") ;}} Public class DaemonsDontRunFinally {public static void main (String [] args) {Thread t = new Thread (new ADaemon (); t. setDaemon (true); t. start ();}}

The final output result is as follows:

Starting ADaemon

However, the output results will be different if the situation changes to the following:

class ADaemon implements Runnable{  @Override  public void run() {    System.out.println("Starting ADaemon");    try {      TimeUnit.SECONDS.sleep(1);    } catch (InterruptedException e) {      System.out.println("Exiting via InterruptedException");    }finally {      System.out.println("This should always run?");    }  }}public class DaemonsDontRunFinally {  public static void main(String[] args) {    Thread t = new Thread(new ADaemon());    t.setDaemon(true);    t.start();    try {      TimeUnit.SECONDS.sleep(1);    } catch (InterruptedException e) {      e.printStackTrace();    }  }}

Because the main thread does not suddenly exit, the background thread gets the execution time during the main thread's sleep, so the final print result is:

Starting ADaemon
This shoshould always run?

Summary

The above is all the content about parsing the background thread instance in Java, and I hope to help you. If you are interested, you can continue to refer to other related topics on this site. If you have any shortcomings, please leave a message. Thank you for your support!

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.