背景:
有时候,我们希望NettyServer启动时不能说卡住主线程。
也不能说:直接就启动一个线程,不然没办法发射出“服务器启动”这个事件。
这时就可以使用此类执行完毕后,通知下主线程。
1)TcpServer.java
package org.example.testStart;import java.io.IOException;
import java.util.concurrent.CountDownLatch;public class TcpServer extends Thread{// 使用这个在当前线程执行完毕后,立马通知主线程private final CountDownLatch latch;public TcpServer(CountDownLatch latch) {this.latch = latch;}@Overridepublic void run() {try {System.out.println(Thread.currentThread().getName() + " tcpserver start success" );latch.countDown();// 相当于netty等待关闭System.in.read();} catch (IOException e) {e.printStackTrace();}}
}
2)Main.java
package org.example.testStart;import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;public class Main {public static void main(String[] args) throws InterruptedException {regHookThread();System.out.println(Thread.currentThread().getName() + " start!");initTcpServer();initTcpServer();System.out.println(Thread.currentThread().getName() + " end!");// 等待5s,模拟使用jmx关闭服务器TimeUnit.SECONDS.sleep(5);System.exit(1);}public static void initTcpServer() throws InterruptedException {CountDownLatch latch = new CountDownLatch(1);new TcpServer(latch).start();// 等待执行完毕latch.await();}public static void regHookThread() {Runtime.getRuntime().addShutdownHook(new Thread(() -> {System.out.println(Thread.currentThread().getName() + " hook thread finish!");}, "gs-hook-thread"));}
}/*
main start!
Thread-0 tcpserver start success
Thread-1 tcpserver start success
main end!
gs-hook-thread hook thread finish!*/
总结:可以看出来,是单独的线程启动,但是可以控制住顺序了。