Xi. handling an uncontrolled exception in a thread group
One important feature of each programming language is the mechanism it provides to handle error conditions in the Program. The Java language, like other modern languages, provides an exception mechanism to handle errors in object Programs. Java provides a number of classes to correspond to different errors. When Java checks for these errors, it throws the corresponding exception Object. You can use the exception classes directly or implement your own exception classes to handle the error cases in the Program.
Java also provides a mechanism for capturing and handling exception Objects. Exceptions must be caught or thrown back. This type of exception is known as a detection exception. There is also a class of exceptions that do not have to be captured and processed, known as Non-detection exceptions.
In this tip, we'll learn how to catch a Non-detection exception thrown by any thread in a thread group.
public classMain { public Static voidmain (string[] Args) {mythreadgroup threadgroup=NewMythreadgroup ("mythreadgroup"); Task Task=NewTask (); for(inti = 0; I < 2; i++) {Thread T=NewThread (threadgroup, task); T.start (); } }} public classMythreadgroupextendsThreadgroup { publicMythreadgroup (String Name) {Super(name); } @Override public voiduncaughtexception (Thread t, throwable e) {System.out.printf ("the thread%s has thrown an exception\n", T.getid ()); E.printstacktrace (system.out); System.out.printf ("terminating the rest of the threads\n"); Interrupt (); } } public classTaskImplementsRunnable {@Override public voidRun () {intresult; Random Random=NewRandom (thread.currentthread (). getId ()); while(true) {result= 1000/((int) (random.nextdouble () *1000)); System.out.printf ("%s:%f\n", Thread.CurrentThread (). getId (), result); if(thread.currentthread (). isinterrupted ()) {System.out.printf ("%d:interrupted\n", Thread.CurrentThread (). getId ()); return; } } }}
12. Create a thread using Factory mode
Factory mode is one of the most used patterns in object-oriented languages. It is a production model that is used primarily to develop an object whose purpose is to generate objects of other Classes. When we want to build objects of other classes, it's good to use the factory object Directly. We use the method of the factory object instead of the new Operator.
The advantages of the factory approach Are:
(A): easy to change the generated Object's class, easy to change the way the production object
(B): easy to control the number of objects produced
(C): easy to count the number of generated objects
Java provides a threadfactory interface to facilitate the use of the Thread object factory. Some JDK use this interface to generate thread Objects.
In this tip, we teach you how to use the Threadfactory interface to create a personalized thread and save statistics on thread creation at the same time.
public classMain { public Static voidmain (string[] Args) {mythreadfactory factory=NewMythreadfactory ("mythreadfactory"); Task Task=NewTask (); Thread thread; System.out.printf ("starting the threads\n"); for(inti = 0; I < 5; i++) {thread=Factory.newthread (task); Thread.Start (); } System.out.printf ("Factory stats:\n"); System.out.printf ("%s\n", Factory.getstats ()); }} public classMythreadfactoryImplementsThreadfactory {Private intcounter; PrivateString name; PrivateList<string>stats; publicmythreadfactory (String Name) {counter= 0; this. Name =name; Stats=NewArraylist<string>(); } @Override publicthread Newthread (Runnable r) {thread t=NewThread (r, name+ "-thread_" +counter); Counter++; Stats.add (string.format ("Created thread%d with name%s on" + "%s\n", t.getid (), t.getname (),NewDate ())); returnt; } publicString getstats () {stringbuffer buffer=NewStringBuffer (); Iterator<String> it =Stats.iterator (); while(it.hasnext ()) {buffer.append (it.next ()); Buffer.append ("\ n"); } returnbuffer.tostring (); } } public classTaskImplementsRunnable {@Override public voidRun () {Try{TimeUnit.SECONDS.sleep (1); } Catch(interruptedexception E) {e.printstacktrace (); } } }
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 VI