java - Exception in a Thread -


I have created a multi-threading program. In it, the main thread starts at 10 threads, but the problem occurs when an exception occurs in one thread, the whole application closes.

  1. But I want that when there are exceptions in one thread, only the thread should stop and continue to work on other threads. How can I do this?

  2. Secondly, I want the main thread to stop after all 10 threads have ended. How can you do this?

You can use (by adding multiple threads) To make your individual items work, call. The present method gives the future, which will include the result of processing or throw any exception . In other words, if an exception occurs, the threads provided under Executable Service will not end.

Example

Be the first to execute a service that contains more than one thread:

  Executable service execService = Exporter . NewfixedThreadPool (5);  

Define the item of the work that we want to submit as a callable :

  public class MyWorkItem Collaborate & lt; Integer & gt; {Public integer call () throws an exception {int result = new random () NextInt (5); // random failure if (result == 0) {new invalid record exception ("failed!"); } Return results; For every  for            Callable & lt; Integer & gt; . 

  list & lt; Future & lt; Integer & gt; & Gt; Forward = new linked list & lt; Future & lt; Integer & gt; & Gt; (); For (int i = 0; i <10; ++ i) {futures.ed (express service submit (new MyWareEtme ()); }  

Repeat the futures that try to get the results of each work item (we can use a completion service for this). < For / p>

  (future  integer> future: futures) {try {integer result = future.get (); } Hold (Exception Pre) {// Handle Exception}}  

Comments

Popular posts from this blog

asp.net - Javascript/DOM Why is does my form not support submit()? -

sockets - Delphi: TTcpServer, connection reset when reading -

javascript - Classic ASP "ExecuteGlobal" statement acting differently on two servers -