惠州企业网站设计,gpl2 wordpress,开发公司项目管理部门获奖主持词,百度推广登录手机版背景#xff1a; 有时候#xff0c;我们希望NettyServer启动时不能说卡住主线程。 也不能说#xff1a;直接就启动一个线程#xff0c;不然没办法发射出“服务器启动”这个事件。 这时就可以使用此类执行完毕后#xff0c;通知下主线程。 1)TcpServer.java
package org.e…背景 有时候我们希望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!*/总结可以看出来是单独的线程启动但是可以控制住顺序了。