简体   繁体   中英

How to exit the application after the thread finished execution

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.

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();   
}
Thread t1 = ...
Thread t2 = ...
t1.join();
t2.join();
System.exit(0);

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

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);

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM