Note that there are some explanatory texts on larger screens.

plurals
  1. POJava Multithread stopping all other threads immediately
    primarykey
    data
    text
    <p>I have this code:</p> <pre><code>public class BruteForceThread implements Callable&lt;String&gt; { private static volatile boolean stopped = false; public String call() { String password = this.getNextPassword(); while (!stopped) { System.out.println(numberOfThreat + ": " + password); synchronized(this) { try { if (this.testPassword(password)) { stopped = true; return password; } } catch (IOException e) { e.printStackTrace(); } } password = this.getNextPassword(); } return ""; } } </code></pre> <p>Main class:</p> <pre><code>public static void main(String[] args) throws IOException { int numberOfThreads = 2; ExecutorService executor = Executors.newFixedThreadPool(numberOfThreads); CompletionService&lt;String&gt; pool = new ExecutorCompletionService&lt;String&gt;(executor); for (int i = 1; i &lt; numberOfThreads + 1; i++) { Callable&lt;String&gt; bruteForce = new BruteForceThread(...); pool.submit(bruteForce); } executor.shutdown(); for(int i = 0; i &lt; numberOfThreads; i++){ try { String result = pool.take().get(); if (result != "") { System.out.println("Your password: " + result); } } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } } executor = null; } </code></pre> <p>Output: ...</p> <pre><code>1: aa &lt;- here first thread found a password 2: Fa &lt;- second thread is continue 2: Fb 2: Fc ... many more ... 2: IZ Your password: aa </code></pre> <p>If one thread find a password and sets stopped to true, another threads does not stop immediately. Why?</p>
    singulars
    1. This table or related slice is empty.
    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. 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