Java多线程-主线程停止

标签 java multithreading

我有一个 Java 应用程序,可以从 IoT 设备读取数据。因为我有智能温度计的例子:

public class Thermometer{

    private final String ip;

    public Thermometer(String ip) {
        this.ip = ip;
    }

    public void startReading () {
        Thread readThread = new Thread(() -> {
            while (true) {
                try {
                    //reading, writing data to DB
                } catch (Exception e) {
                    //logging
                }
            }
        });
        readThread.start();
    }
}

在我的主目录中,我添加了所有 IoT 设备并启动它们的阅读线程:

new Thermometer("192.168.1.100").startReading();
new Thermometer("192.168.1.101").startReading();

过了一会儿(我上次尝试大约 12 小时),我的主线程停止了,所以我的所有线程也停止了。 我的日志文件(log4j2)有一行关于此内容:

com.foo.Main - null

可能完整的堆栈跟踪已打印到 sys.err。我会尽力捕获它并更新帖子。

为什么会发生这种情况?如何启动所有线程以便它们永远运行?

UPD。主类:

public class Main {

    public static void main(String[] args) {
        new Thermometer("192.168.1.100").startReading();
        new Thermometer("192.168.1.101").startReading();
    }
}

UPD2。启动脚本:

nohup java -Dlog4j.configurationFile=$PATH_TO_LOG4J2_XML -jar $PATH_TO_REEVE_JAR >> /home/buger/reeve/nohup.log 2>>&1 &
echo $! > $PATH_TO_PID
echo_and_log "Successfully started! PID = `cat $PATH_TO_PID`"

最佳答案

我认为您的读者线程出了问题。也许是一个异常(exception),achem,一个Error杀了他们。我建议你调试一下。

同时,这里有一个示例代码,可以证明我的理论:

public class Main {

    public static void main(String[] args) {
        Thread thread1 = new Thread(() -> {
            while (true) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("--> thread 1");
            }
        });
        Thread thread2 = new Thread(() -> {
            while (true) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("--> thread 2");
            }
        });
        thread1.start();
        thread2.start();
        System.out.println("--> main thread about to finish");
    }

}

这会产生以下输出:

--> main thread about to finish
--> thread 2
--> thread 1
--> thread 1
--> thread 2
...

关于Java多线程-主线程停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53719641/

相关文章:

multithreading - 线程安全的优先队列

c++ - 在原子多线程代码中删除容器

java - 获取对象在 Java 列表中的索引

java - selenium ide 导出到 webdriver java

java - Neo4j重新连接数据库后无法获取所有节点

java并发实践16.1

.net - 如何添加任务优先级功能

c# - ping 多个 IP 会使我的网络繁忙吗?

java - 单个浏览器中的多个 session

java - 使用仅调用重写的父类(super class)方法的子类方法有好处吗?