43. Daemon Threads and Join methods

Source: Internet
Author: User

1. Daemon thread (Background thread):
when we use a software, some software will let us do not know the situation to download something, then this is the background thread.
generally used to increase the amount of software downloaded (that is, to earn some advertising costs)
            
Setdaemon (Boolean B) setting is a daemon thread
Isdaemon () returns whether it is a daemon thread (true no false)
Note: When the program stops running, the daemon thread must also stop

let's simulate using QQ, then download a software in the background

 Public classDemo11Implementsrunnable{@Override Public voidrun () { for(inti = 1; I <= 100; i++) {System.out.println ("Current Download" +i+ "%"); }    }     Public Static voidMain (string[] args) {Demo11 d=NewDemo11 (); Thread Thread=NewThread (d); Thread.setdaemon (true);//Set as daemon threadThread.Start (); //QQ Program stops when I is 100         for(inti = 0; I < 100; i++) {System.out.println ("Use QQ" +i); }    }}

2.join join:

When you use this method in a thread task body (run), you must wait until the thread that calls the Join method finishes the task before the task body can continue execution

code example:

classThread2Implementsrunnable{@Override Public voidrun () { for(inti = 0; I < 20; i++) {System.out.println (Thread.CurrentThread (). GetName ()+":"+i); }        }} Public classDemo12Implementsrunnable{@Override Public voidrun () { for(inti = 0; I < 100; i++) {            if(i==30) {Thread2 T=NewThread2 (); Thread Thread=NewThread (t, "joined thread");                Thread.Start (); Try{thread.join ();//Join a thread}Catch(interruptedexception e) {//TODO auto-generated Catch blockE.printstacktrace (); }} System.out.println (Thread.CurrentThread (). GetName ()+":"+i); }    }         Public Static voidMain (string[] args) {Demo12 d=NewDemo12 (); Thread Thread=NewThread (d, "joined thread");    Thread.Start (); }}

43. Daemon Threads and Join methods

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.