[Javase] Multithreading (daemon thread)

Source: Internet
Author: User

We generally use multi-threading, which is the dead loop of the while, want to end the thread, just exit the dead loop to

When the sleep () method or the Wait () method is called in the thread , the current thread goes into a frozen state and the thread ends

Calling the interrupt () method of the Thread object can be forced to thaw, at which point the run () method needs to capture the Interruptexception The exception, and then processing it, you can close the thread.

Call the Setdaemon () method of the Thread object , Parameter:true

The daemon thread is a background thread, and the background thread ends automatically when the current thread is all over.

classTicketImplementsRunnable {Private intNums = 100; @Override Public voidrun () { while(true) {            synchronized( This) {                if(Nums > 0) {                    Try{Thread.Sleep (100); } Catch(Exception e) {e.printstacktrace (); } System.out.println (Thread.CurrentThread (). GetName ()+ "= = =" + (nums--)); }Else{                     Break; }            }        }    }} Public classTicketdemo {/**     * @paramargs*/     Public Static voidMain (string[] args) {Ticket Ticket=NewTicket (); Thread T1=NewThread (ticket); Thread T2=NewThread (ticket); T1.setdaemon (true); T2.setdaemon (true);        T1.start ();                T2.start (); //The main thread executes in 1 seconds, and the other daemons will end before they're finished.         while(true){            Try{Thread.Sleep (1000);  Break; } Catch(Exception e) {e.printstacktrace (); }        }    }}

[Javase] Multithreading (daemon thread)

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.