Reputation: 426
I am newb to java execuatorservice.
i went threw some examples in internet but i have some basic doubt.
i created a callable class like below
public class ReadTest implements Callable<String> {
@Override
public String call() throws Exception {
return "OK";
}
}
and i created my main class like below
public class ThreadMain {
public static void main(String args[]) {
try {
ExecutorService execuator = Executors.newFixedThreadPool(5);
for (int i = 0; i < 10; i++) {
Future<String> future;
System.out.println("I : " + i);
future = execuator.submit(new ReadTest());
System.out.println(future.get());
future.cancel(true);
}
execuator.shutdownNow();
} catch (Exception ex) {
System.out.println("Error : " + ex);
}
}
}
i am creating FixedThreadPool with limit 5. my loop is running up to 10 times. 1. Here how many threads will be created and used.(according to my view only one thread used, because i cancel with future object every time. is it correct?)
2.i want to execute multiple tasks like above for loop. i have list of commands to execute in shell using jsch. how to do this with threads ?
any help will be appreciated
Upvotes: 0
Views: 2859
Reputation: 10400
Are you trying to run async tasks, must do something else while waiting? Maybe this is not what you are looking for but you were studying java executorservice. This app uses async concurrent threads what you were looking for?
public class ThreadMain {
public static void main(String args[]) {
try {
// start async(threaded) workers
ExecutorService execuator = Executors.newFixedThreadPool(5);
List<Future<String>> workers = new ArrayList<Future<String>>();
for (int idx=0; idx < 10; idx++)
workers.add( execuator.submit(new ReadTest()) );
// loop until all workers is done, results may arrive in random order,
// if none is ready then do something else while waiting for next result.
while(!workers.isEmpty()) {
Future<String> worker=null;
for(int idx=0; idx < workers.size(); idx++) {
worker = workers.get(idx);
if (worker.isDone()) {
worker.remove(idx);
break;
}
worker = null;
}
if (worker==null) {
Thread.sleep(500); // do something else, like idle
} else {
System.out.println("Worker is done with results " + worker.get() );
}
}
execuator.shutdown();
} catch (Exception ex) {
System.out.println("Error : " + ex);
}
}
}
Upvotes: 1