Hi!
I'm a begginer in the use of ExecutorService and I don't know if I can do what I pretend.
Now I have a program that perform different calculations and I did it using an array of Threads. When I need use more than one thread for a particular calculation, I use a semaphore. When I find a valid result, I use it to terminate all the threads.
Recently I saw the advantages of the use of threadPool. for example, No need to be looking for a place to launch the next thread, because this is managed directly by the pool
The problem I found is that I don't know if I can use the threadPool or other Object from the concurrent package for terminated a group of threads without doing a shutdown of the ThreadPool.
I attach a code with a simple example. This code creates 10 threads that end up randomly, accord to the random times generated. I've added an id with the value 5 in the definition of the first 5 threads and a value of 10 for the rest. The change I want to do in the original example is that when a thread of the second group (id = 10) is finished, all the threads with id = 5 must be terminated inmediately but the rest must continue even the end.
import java.util.concurrent.*;
import java.util.*;
public class Example implements Runnable {
private static Random random = new Random();
private String payload;
private String id;
public Example (String someString, String id) {
this.payload = someString;
this.id = id;
}
public String getPayload() {
return this.payload;
}
public String getId() {
return this.payload;
}
public void run () {
int seconds = random.nextInt(10);
//seconds = random.nextInt(seconds);
long totalSleep = 1000l*seconds;
System.out.println ("SLEEP " + this.payload + " " + totalSleep);
try {
System.out.println("BEGIN " + this.payload);
Thread.sleep(totalSleep);
} catch (InterruptedException tie) {
throw new RuntimeException("I got interrupted");
}
System.out.println("END " + this.payload);
}
public static void main (String[] args) {
ExecutorService es = Executors.newFixedThreadPool(5);
List<Future<Example>> tasks = new ArrayList<Future<Example>>();
for (int x=0; x<10; x++) {
String name = "I am thread number: " + x;
String ide = "5";
if (x >= 5)
ide = "10";
Example e = new Example(name, ide);
Future<Example> future = es.submit(e, e);
tasks.add(future);
} // -- all threads should be launching, let's get the Example objects
try {
for (Future<Example> future : tasks) {
Example e = future.get();
System.out.println(" [future complete]: " + e.getPayload());
}
es.shutdown();
} catch (ExecutionException e) {
throw new RuntimeException(e);
} catch (InterruptedException ie) {
throw new RuntimeException(ie);
}
}
}
If someone can help me, I will be eternally gratefully.
Regards.