Search code examples
javamultithreadingwait

I can't wait my Threads in java


I have problems in mulithreads environment . I can create several threads that execute correctly, However the process never end. I can't wait for the finishing. I want to do some action when all my threads end but currently it is impossible. Here my code:

public static void main(String[] args){

 public void run(){
            ExecutorService exec = Executors.newFixedThreadPool(10);
    try {
                for(int i=0;i<100;i++){
                    final Integer a=i;
                    try {
                        exec.submit(new Runnable() {
                        @Override
                            public void run() {  

                        System.out.println(a);
                        }
                     });
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
            catch(Exception e){
                e.printStackTrace();
            }
        }
}

Someone knows how to achieve my goal? Thanks!


Solution

  • Don't create a thread and an ExecutorService. That's redundant.

    Currently, your program isn't exiting because the main thread called wait() but no other thread is calling notify().

    If you want the main thread to wait until all of the tasks finish, do something like this:

    final class EjecutorUpdateContactos {
      void update() throws Exception {
        ExecutorService workers = Executors.newFixedThreadPool(10);
        List<Callable<Void>> tasks = new ArrayList<>();
        for(int i = 0; i < 100; i++) {
          int a = i;
          tasks.add(new Callable<Void>() {
            @Override
            public Void call() {
              System.out.println(a);
              return null;
            }
          });
        }
        workers.invokeAll(tasks);
        workers.shutdown();
      }
    }