簡體   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