Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <blockquote> <p>I want in case one of them throws an exception and dies to be replaced by another NEW thread. </p> </blockquote> <p>I don't quite understand why you can't do:</p> <pre><code>public void run() { // only quit the loop if the thread is interrupted while (!Thread.currentThread().isInterrupted()) { try { // do some stuff that might throw repeat task; } catch (Exception e) { // recover from the throw here but then continue running } } } </code></pre> <p>Why do you need to restart a NEW thread? Just because a task threw an exception doesn't mean that it is somehow corrupt and it needs a fresh one to work appropriately. If you are trying to catch <em>all</em> exceptions (including <code>RuntimeException</code>) then <code>catch (Exception e)</code> will do this. If you want to be <em>really</em> careful you can even catch <code>Throwable</code> in case there is a chance that <code>Error</code>s are being generated – this is relatively rare.</p> <p>If you actually have multiple tasks (or really anytime you are dealing with threads), you should consider using the <code>ExecutorService</code> classes. See the <a href="http://docs.oracle.com/javase/tutorial/essential/concurrency/exinter.html" rel="nofollow noreferrer">Java tutorial</a>.</p> <pre><code>// create a thread pool with 10 workers ExecutorService threadPool = Executors.newFixedThreadPool(10); // or you can create an open-ended thread pool // ExecutorService threadPool = Executors.newCachedThreadPool(); // define your jobs somehow threadPool.submit(new Class1()); threadPool.submit(new Class2()); ... // once we have submitted all jobs to the thread pool, it should be shutdown threadPool.shutdown(); </code></pre> <p>So instead of forking a thread to do multiple tasks, you start a thread pool and it starts threads as necessary to accomplish a bunch of tasks. If a task fails, you could certain submit another task to the pool although that's a slightly strange pattern.</p> <p>If you want to wait for all of the tasks to finish you'd use:</p> <pre><code>threadPool.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS); </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload