繁体   English   中英

线程完成执行后如何退出应用程序

[英]How to exit the application after the thread finished execution

我有以下代码

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

我想等待两个步骤完成执行,然后使用System.exit(0);退出应用程序System.exit(0); 我怎样才能做到这一点?

有人可以帮我吗。

您将需要在两个线程上使用join()

根据官方文件

join方法允许一个线程等待另一个线程的完成。 如果t是当前正在执行其线程的Thread对象,则t.join()导致当前线程暂停执行,直到t的线程终止。

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

您需要捕获InterruptedException或将main标记为也将其抛出。

您可以使用.join() ,它将阻塞直到线程执行完毕。

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

如果要终止流,请使用System.exit(0)

要么

您可以简单地将对所有线程的引用保留在某个地方(例如列表),然后在以后使用引用。

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

每次启动线程时:

线程线程=新线程(新MyRunnable()); appThreads.add(thread); 然后,当您要发出终止信号(不是希望通过停止信号,我希望:D)时,您可以轻松访问所创建的线程。

您也可以使用ExecutorService并在不再需要它时调用shutdown:

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

这样会更好,因为您不应为要执行的每个任务真正创建一个新线程,除非它长期运行I / O或类似的东西。

请注意,您不应直接创建线程。 使用ExecutorService启动异步任务:

ExecutorService executor = Executors.newFixedThreadPoolExecutor(4);
executor.submit(() -> employee1());
executor.submit(() -> employee2());
executor.shutdown();
executor.awaitTermination(timeout, TimeUnit.MILLISECONDS);
// all tasks are finished now

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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