Java 7 Concurrency Cookbook Translation The first chapter of thread management four

Source: Internet
Author: User
Tags stack trace thread class

Vii. creating and running a background thread

There is a special thread in Java called a deamon (background) thread. Such threads have very low permissions and only run when no other normal thread is running in the same program. Note: When only a background thread is left in a program, the JVM will terminate all background threads and end the program.

Because of this feature, a background thread is typically used to serve other normal threads in the same program. This background thread typically has an infinite loop waiting for the request service or performing the requested task. Background threads cannot be used to perform important tasks because they do not know when they can get the CPU's call execution and are terminated by the JVM without other normal threads. A typical application of a background thread is the garbage collector in Java.

In this tip, we'll learn how to create a program with two threads: a normal thread writes an event on one queue, and another background thread cleans up events generated 10 seconds ago on that queue.

  

 Public classCleanertaskextendsThread {PrivateDeque<event>deque;  PublicCleanertask (deque<event>deque) {         This. deque =deque; Setdaemon (true); } @Override Public voidrun () { while(true) {Date Date=NewDate ();        Clean (date); }    }        Private voidClean (date date) {Longdifference; BooleanDelete; if(deque.size () = = 0) {            return; } Delete=false;  Do{Event e=Deque.getlast (); Difference= Date.gettime ()-e.getdate (). GetTime (); if(Difference > 1000) {System.out.println ("Cleaner:" + e.getevent () + "\ n");                Deque.removelast (); Delete=true; }        }  while(Difference > 1000); if(delete) {System.out.printf ("Cleaner:size of the queue:" + deque.size () + "\ n"); }    }    } Public classEvent {PrivateDate date; PrivateString event;  PublicDate getDate () {returndate; }     Public voidsetDate (date date) { This. Date =date; }     PublicString getEvent () {returnevent; }     Public voidsetEvent (String event) { This. event =event; }    } Public classMain { Public Static voidMain (string[] args) {Deque<Event> deque =NewArraydeque<event>(); Writertask writer=NewWritertask (deque);  for(inti = 0; I < 3; i++) {thread thread=NewThread (writer);        Thread.Start (); } Cleanertask Cleaner=NewCleanertask (deque);    Cleaner.start (); }} Public classWritertaskImplementsrunnable{PrivateDeque<event>deque;  PublicWritertask (deque<event>deque) {         This. deque =deque; } @Override Public voidrun () { for(inti = 1; I < 20; i++) {Event Event=NewEvent (); Event.setdate (NewDate ()); Event.setevent (String.Format ("The thread%s has generated" + "an event", Thread.CurrentThread (). GetId ());            Deque.addfirst (event); Try{TimeUnit.SECONDS.sleep (1); } Catch(interruptedexception e) {e.printstacktrace (); }        }    }        }    

Note: the Setdeamon () method must be called before the start () method is valid. Once the thread is started, it cannot be modified to be a background thread. At the same time, you can use the Isdeamon () method to determine whether a thread is a background thread.

VIII. handling exceptions that are not controlled in the thread

There are two types of exceptions in Java:

(A) anomaly detection: Must be caught or thrown.

(B) No exception detected: Can not be captured.

Because the Thread object's run () method cannot throw an exception, the detection exception that appears in this method must be captured. When an exception is thrown in the run () method, the default behavior of the thread object is to write the thread stack information to the console and then exit the program.

Fortunately, Java provides a mechanism that allows us to capture and transform undetected exceptions, so that we can avoid program termination due to exceptions thrown in the run () method.

There is a Uncaughtexceptionhandler interface in Java to handle uncaught exceptions.

 Public classExceptionhandlerImplementsuncaughtexceptionhandler{@Override Public voiduncaughtexception (Thread T, Throwable e) {System.out.println ("An exception have been captured"); System.out.println ("Thread:" +T.getid ()); System.out.println ("Exception:" + e.getclass (). GetName () + ":" +e.getmessage ()); System.out.println ("Stack Trace:");        E.printstacktrace (System.out); System.out.println ("Thread Status:" +t.getstate ()); }} Public classMain { Public Static voidMain (string[] args) {Task Task=NewTask (); Thread Thread=NewThread (Task); Thread.setuncaughtexceptionhandler (NewExceptionhandler ());    Thread.Start (); }} Public classTaskImplementsRunnable {@Override Public voidrun () {Integer.parseint ("TTT"); }    }

When an exception is thrown in the thread, the JVM first checks to see if the thread has set the thread exception handler and, if there is one, calls the processor to handle the exception. If not, the default behavior of the JVM is to print the thread stack information to the console while the program is rolled out.

Note: The Thread class has a static method Setdefaultuncaughtexceptionhandler () to set the processor for all uncaught exceptions in the program. When an uncaught exception is thrown in the thread: the JVM first checks to see if the thread has set the corresponding thread exception handler, if the thread group that the thread belongs to does not have a set thread exception handler, if it has not yet checked whether the program has set the default thread exception handler.

If no exception handler exists, the JVM performs the default behavior: Write line Cheng information to the console and terminate the program's operation.

Important: This series of translation documents will also be in my public number (this mountain is my opening) the first time to publish, welcome attention.

Java 7 Concurrency Cookbook Translation The first chapter of thread management four

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.