即使在main中的最后一条语句之后,Java程序仍继续运行(在后台)

即使在main中的最后一条语句之后,Java程序仍继续运行(在后台),java,linux,bash,background-process,Java,Linux,Bash,Background Process,背景 我有一个简单的java程序,可以从std输入读取数据。我是通过bash脚本执行它的executer.sh python2 readLines.py | tee logfile | java MsgReader readLines.py逐行从文件中读取数据并将其抛出标准输出 MsgReader.java 执行 /executer.sh&:在后台执行 问题 读取所有行后,readLines.py结束,但是executer.sh和MsgReader.java通过ps命令验证stll正在执行。

背景

我有一个简单的java程序,可以从std输入读取数据。我是通过bash脚本执行它的
executer.sh

python2 readLines.py | tee logfile |  java MsgReader
readLines.py
逐行从文件中读取数据并将其抛出标准输出

MsgReader.java

执行

/executer.sh&
:在后台执行

问题

读取所有行后,
readLines.py
结束,但是
executer.sh
MsgReader.java
通过
ps
命令验证stll正在执行。语句
System.out.println(“之后:+now”)操作系统,表示程序已到达主函数中的最后一条语句

如何优雅地终止java程序和bash脚本

我不想在这里添加
System.exit()

平台

CentOS 6.7版(最终版)

java 1.7.0_95


python 2.7.6

您没有关闭生产者。从
KafkaProducer
的Javadoc(实现
Producer
):

生产者包括一个缓冲空间池,其中保存尚未传输到服务器的记录,以及一个后台I/O线程,负责将这些记录转换为请求并将其传输到集群。如果使用后未关闭生产商,则会泄漏这些资源


后台线程仍在运行,并将阻止进程结束,直到您关闭
生产者
,最好在
try
/
catch
之后的
finally
块中。还有,
stdinReader.close()最终也属于
中。

处理
的功能是什么?它可能非常相关,特别是因为它听起来可能是某种类型的异步任务执行器。考虑退房,什么是P?请显示代码如果在前台运行该怎么办?我试图解决的问题与过程方法AFAIK无关。那部分很好用。我更感兴趣的是试图理解在后台运行的进程需要特殊处理才能完成。
过程
方法具有更复杂的逻辑,尽管如此,我还是尝试将其简化。让我们看看它有什么帮助。@Jim现在是了(之前没有任何代码)。去争取吧
import kafka.javaapi.producer.Producer;

public void process() {
    String msg = ""; 
    BufferedReader stdinReader = new BufferedReader(new InputStreamReader(System.in)

    Producer producer = new Producer();//it takes config file as parameter which is not related to the question here

    try {
         while ((msg = stdinReader.readLine()) != null) {
              producer.send(message);
         }   
         stdinReader.close();
     } catch (IOException|FailedToSendMessageException e) {
            System.out.println("Send message failed!");
            e.printStackTrace();
     }   
}   

public static void main(String args[]) throws JSONException,IOException {
    try{
        Date now = new Date();
        System.out.println("Start : " + now);
        process();// Continuously reads logs
        now = new Date();
        System.out.println("After : " + now);
    } catch(Exception e){ 
        e.printStackTrace();
        return;
    }   
}