0

I have the following code

    public static void main(String[] args) {
    new Thread() { 
        public void run() {
            try {
                employee1();
            } catch (Exception e) {
                Logger.LogServer(e);
            }
            finally {
                Logger.LogServer("empployee1 records inserted");
          }
        }
    }.start();
    new Thread() { 
        public void run() {
            try {
                employee2();
            } catch (Exception e) {
                Logger.LogServer(e);
            }
            finally {
                Logger.LogServer("employee2 records inserted");
          }
        }
    }.start();
}

I want to wait for both the treads to finish execution and then exit the application with System.exit(0);. How can i achieve this?

Can someone please assist me.

Sai Avinash
  • 287
  • 4
  • 7
  • 17
  • add two flags, one for each thread. only put it to true if the thread is finished, when both are true, finish – Stultuske Mar 19 '18 at 11:31
  • 4
    Call `join()` on the threads . – Arnaud Mar 19 '18 at 11:31
  • Possible duplicate of [How to wait for threads to complete in Java where threads are initiated using run()](https://stackoverflow.com/questions/33397934/how-to-wait-for-threads-to-complete-in-java-where-threads-are-initiated-using-ru) – Piro Mar 19 '18 at 11:31
  • Possible duplicate of [Waiting on multiple threads to complete in Java](https://stackoverflow.com/questions/1361029/waiting-on-multiple-threads-to-complete-in-java) – AxelH Mar 19 '18 at 11:32
  • It already does. – matt Mar 19 '18 at 11:33
  • Note that it is only need if you want to do something before the program exits (print a log or something) after both threads are over. `System.exit(0);` is not needed. – AxelH Mar 19 '18 at 11:35
  • @AxelH yeah i'm trying to print a log before the app completely exits. – Sai Avinash Mar 19 '18 at 11:53

5 Answers5

4

You would need to use join() on both threads.

As per the official documentation:

The join method allows one thread to wait for the completion of another. If t is a Thread object whose thread is currently executing, t.join() causes the current thread to pause execution until t's thread terminates.

public static void main(String[] args) {
    Thread t1 = new Thread() { 
        public void run() {
            ...
        }
    };
    Thread t2 = new Thread() { 
        public void run() {
            ...
        }
    };

    t1.start();
    t2.start();

    t1.join();
    t2.join();   
}
Alexandre Dupriez
  • 3,026
  • 20
  • 25
1
Thread t1 = ...
Thread t2 = ...
t1.join();
t2.join();
System.exit(0);

You need to catch InterruptedException or mark main as throwing it as well.

ewramner
  • 5,810
  • 2
  • 17
  • 33
0

You can use .join() that will block until the thread has finished executing.

Thread t = new Thread() { 
    public void run() {
        try {
            employee1();
        } catch (Exception e) {
            Logger.LogServer(e);
        }
        finally {
            Logger.LogServer("empployee1 records inserted");
      }
    }
}.start();
Thread t2 = new Thread() { 
    public void run() {
        try {
            employee2();
        } catch (Exception e) {
            Logger.LogServer(e);
        }
        finally {
            Logger.LogServer("employee2 records inserted");
      }
    }
}.start();
t.join();t2.join();
System.exit(0);
Skizo-ozᴉʞS ツ
  • 19,464
  • 18
  • 81
  • 148
0

if you want to terminated the flow use System.exit(0)

or

You can simply keep references to all the threads somewhere (like a list) and then use the references later.

List<Thread> appThreads = new ArrayList<Thread>();

Every time you start a thread:

Thread thread = new Thread(new MyRunnable()); appThreads.add(thread); Then when you want to signal termination (not via stop I hope :D) you have easy access to the threads you created.

You can alternatively use an ExecutorService and call shutdown when you no longer need it:

ExecutorService exec = Executors.newFixedThreadPool(10);
...
exec.submit(new MyRunnable());
...
exec.shutdown();

This is better because you shouldn't really create a new thread for each task you want to execute, unless it's long running I/O or something similar.

abhinavsinghvirsen
  • 1,853
  • 16
  • 25
0

Note that you should not create Threads directly. Use an ExecutorService to start asynchronous tasks:

ExecutorService executor = Executors.newFixedThreadPoolExecutor(4);
executor.submit(() -> employee1());
executor.submit(() -> employee2());
executor.shutdown();
executor.awaitTermination(timeout, TimeUnit.MILLISECONDS);
// all tasks are finished now
daniu
  • 14,137
  • 4
  • 32
  • 53
  • from the javadocs > This method does not wait for previously submitted tasks to complete execution. Use awaitTermination to do that. – matt Mar 19 '18 at 11:53