我有以下代码
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);退出应用程序。我怎样才能做到这一点?
有人能帮帮我吗。
发布于 2018-03-19 11:32:14
您需要在两个线程上使用join()。
根据正式文件
联接方法允许一个线程等待另一个线程的完成。如果t是线程当前正在执行的线程对象,
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();
}发布于 2018-03-19 11:32:20
Thread t1 = ...
Thread t2 = ...
t1.join();
t2.join();
System.exit(0);您需要捕获InterruptedException或标记main以及抛出它。
发布于 2018-03-19 11:33:16
您可以使用.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);https://stackoverflow.com/questions/49361881
复制相似问题