需求:
main方法中创建了线程,子线程没有执行结束的时候主线程执行结束了,利用join又不能保证并发执行,目的是主线程等待其子线程执行完成之后退出
实现:
利用Hook实现jvm的等待执行
业务线程:
class CustomerThread implements Runnable {
@Override
public void run() {
System.out.println("***************CustomerThread********");
try {
Thread.sleep(1 * 1000l);
System.out.println("***************CustomerThread end********");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
main方法调用:
public static void main(String[] args) throws Throwable {
for (int i = 0; i < 10; i++) {
Thread t = new Thread(new CustomerThread());
Runtime.getRuntime().addShutdownHook(t);
}
}
jvm调用满足需求