在 Java 中创建等待线程的 main() 循环的黄金标准是什么

安德烈亚斯·希斯

我的任务是编写一个小型服务器应用程序。它应该通过控制台启动,然后在后台运行,处理一些网络流量并在本地计算内容,直到它收到关闭信号。我很确定我可以处理所有这些 - 除了非常基本的应用程序架构。我非常不确定如何让我的主循环等待应用程序完成。所以这是我当前的代码,清理并省略了不必要的部分。

public class TestServer {

public static Logger logger;
private static Boolean abortStartup = false;
private static ServerModule server;

public static void main(String[] args) {
    System.out.println("Starting Server...");
        initializeServer(); //this function reads config file, and initializes all variables and stuff. If anything goes wrong, abortStartup is set to true

        if (!abortStartup) {
            runMainLoop();              
        }

        if (!abortStartup) {
            cleanup(); //clean up all initialized variables and objects
        }

    System.out.println("Goodbye.");
}


private static void runMainLoop() {
    //This is the main loop. Run this until application terminates.
    logger.log(null, "Starting main loop...", Logger.LOGLEVEL_NOTE);
        server.run();
        while (server.isAlive()) {
            //wait until server dies.
            try {
                Thread.sleep(10000);
            } catch (InterruptedException e) {
                logger.log(null, "Interrupted during wait for main thread.", Logger.LOGLEVEL_ERROR);
            }
        }
    logger.log(null, "Done.", Logger.LOGLEVEL_NOTE);
}

ServerModule 看起来像这样:

public class ServerModule{

public Boolean shutdown = false;
private Boolean stayAlive = true;


public ServerModule(){
    //setup everything
}

public void run() {
    //initalize timers, instantiate objects etc.. add listeners and everything. At some point, a network message will set stayAlive to false;
}

public Boolean isAlive() {
    return stayAlive;
}

现在是实际问题:有没有更优雅或更有效的方法来解决这个问题?我特别在谈论这部分:

while (server.isAlive()) {
            //wait until server dies.
            try {
                Thread.sleep(10000);
            } catch (InterruptedException e) {
                logger.log(null, "Interrupted during wait for main thread.", Logger.LOGLEVEL_ERROR);
            }

thread.sleep 在这里好吗?我什至可以或应该省略它吗?我想在我的代码的这一点上等待,这样我就可以在执行停止后进行清理。

ΦXocę 웃 Пe peúpa tsu

您可以使您的服务器具有可运行性,将其打包到一个线程中并加入!

例子

public static void main(String[] args) throws InterruptedException {
    Thread t = new Thread(() -> {
        try {
            Thread.sleep(5000L);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    });
    System.out.println("Starting Server!");
    t.start();
    t.join();
    System.out.println("Server is done!");

}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

Java中组件的基准是什么

Main方法等待执行中的线程完成。为什么?

为什么线程“ main”中的异常java.lang.NoClassDefFoundError :?

为什么线程比Java中的main方法寿命更长?

在JSON中定义空对象的标准是什么

在子类中引发异常的标准是什么

codeigniter中查询编写的标准是什么

在gcc中包含语言的标准是什么?

为什么我在递归 java 方法中收到“线程“main”java.lang.StackOverflowError 中的“异常”?

为什么Main在旋转新线程时会等待,而在任务中却没有等待

(更新)QT QML 5.6-是什么导致此警告“ QApplication未在main()线程中创建”?

线程main中的java.lang.StackOverflowError

为什么main方法在Java中是静态的

锯齿状数组循环中线程“main”java.lang.ArrayIndexOutOfBoundsException中的错误异常

为什么在线程“ main” java.util.NoSuchElementException中得到异常?

为什么我得到此“线程“ main”中的异常” java.util.InputMismatchException”?

Java中main()方法和主线程之间有什么关系?

在Java中唤醒等待线程

'src / main / java'约定的优点是什么?

java错误:线程“ main”中的异常java.lang.NoClassDefFoundError

线程“main”java.lang.RuntimeException 中的 flink-quickstart-java 异常:尚未创建数据接收器

为什么会抛出此错误:线程“main”中的异常 java.lang.OutOfMemoryError: Java heap space?

Go中多词结构类型的命名标准是什么?

对于具有相同值的字段,firestore 中的默认“orderBy”标准是什么?

testng中的线程“ main”中的异常java.lang.NoClassDefFoundError

Java:如何在不覆盖 main 的情况下在类中创建无限循环

如何使用Java中的循环创建多个线程

Java main方法中的循环和异常处理

ideone上的线程“ main”中的异常java.util.NoSuchElementException