Good day! I have a task to make ScheduledThreadPool , stuff the execute threads into it, and stop the current thread until all the others are executed or they hang . I mean that there may be such a situation that at least 1 thread will be interrupted (it is Runnable that is being executed, no exceptions are thrown out), it is necessary in this case that the weightings would be finalized and the main thread would continue execution. I tried awaitTerminator , but it does not respond to the interrupted flow and continues to wait for a timeout. Are there any other solutions? thank
- Why use ScheduledThreadPool and wait for tasks in the main thread? Does Scheduled not mean that tasks are scheduled? Maybe you are interested in the question, how to run N tasks and wait for their execution in the main thread? - a_gura
- Yes, that’s what interests me - voipp
|
2 answers
Arrange your tasks as Future and use the invokeAll method
List<Future> futures = new ArrayList<Future>(); futures.add(f1); futures.add(fn); List<Future> results = executor.invokeAll(futures); //блокирует основной поток в ожидании завершения всех задач.
If necessary, in the invokeAll
call, invokeAll
can set a timeout to wait for the completion. Then go over all the results. Those Future
instances that ended correctly will return true
when isDone
called, and the result can be obtained using the get
method.
|
Your task is not very clear.
Probably you can handle errors in the stream:
Thread t = new Thread(new Runnable(){ public void run() { throw new RuntimeException(); } }); t.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() { public void uncaughtException(Thread t, Throwable e) { System.out.println("exception " + e + " from thread " + t); } }); t.start();
- I meant that it was necessary for me that the main thread after running all the other threads ( ScheduledThreadPool.execute ) stopped and waited until they were completed. But there is only one problem, all of a sudden some threads will stop, and the rest will work. Will the main thread end? There is a suggestion to use awaitTerminator - voipp
|