Java Foundation---->java Multi-threaded use (v)

Source: Internet
Author: User

There are two kinds of threads in a Java thread, one is a user thread and the other is a daemon thread. A daemon thread is a special thread that is automatically destroyed by a daemon thread when there is no non-daemon thread in the process. Today we will learn about the daemon thread in Java using an example.

Examples of daemon threads in Java-Simple use of daemon threads in Java
 PackageCom.linux.thread;ImportJava.util.concurrent.TimeUnit; Public classMyThreadextendsThread {Private inti = 0; @Override Public voidrun () {Try {             while(true) {i++; System.out.println ("I =" +i); TimeUnit.SECONDS.sleep (1); }        } Catch(interruptedexception e) {e.printstacktrace (); }    }}

The contents of the subject class of the test are as follows:

 PackageCom.linux.thread;ImportJava.util.concurrent.TimeUnit; Public classMythreadrun { Public Static voidMain (string[] args) {Try{MyThread thread=NewMyThread (); Thread.setdaemon (true);            Thread.Start (); TimeUnit.SECONDS.sleep (5); System.out.println ("Liberty consists in doing what one desires.");//when the main thread executes this, the daemon stops executing. }Catch(interruptedexception e) {e.printstacktrace (); }    }}

The results of one run are as follows:

12 3 4 5 in doing What one desires.

After the main thread execution is destroyed (after all non-daemon threads have finished executing), all daemon threads are automatically destroyed.

Friendship Link

Java Foundation---->java Multi-threaded use (v)

Related Article

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.