Several threads are created in the loop.

// Открыли соединение с базой for (int i = 0; i < 3; i++) { new Thread(new Runnable() { public void run(){ // Выполнили обращение к базе } }).start(); } // Закрыли соединение с базой 

If I try to close the connection to the database before the call is made from one of the threads, an exception is thrown. How to wait for the completion of all threads?

    4 answers 4

    Option based on thread.join() :

     List<Thread> threads = new ArrayList<Thread>(); for (int i = 0; i < 3; i++) { threads.add(new Thread(new Runnable() { public void run() { // ... } })); } for (Thread thread: threads) { thread.start(); } for (Thread thread: threads) { thread.join(); } 

      I know, I was late for 5.5 years, but still - there is a class java.util.concurrent.CyclicBarrier, in which you can specify the number of threads that should go into it so that it misses them all

        You need to use TheadPool, ThreadPoolExecutor, or close the database in each thread.

          Perhaps worth a look at this class . Or in the old manner to use semaphores.