Sytem.exit vs break或return

Aru*_*mar 2 java activemq-classic

我正在执行以下ActiveMq程序,将文件放入队列中.

public static void main(String[] args) throws JMSException, IOException {
    FileInputStream in;
    //Write the file from some location that is to be uploaded on ActiveMQ server

    in = new FileInputStream("d:\\test-transfer-doc-1.docx");
    ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(
                    "tcp://localhost:61616?jms.blobTransferPolicy.defaultUploadUrl=http://admin:admin@localhost:8161/fileserver/");
    ActiveMQConnection connection = (ActiveMQConnection) connectionFactory
                    .createConnection();
    connection.start();
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    Queue destination = session.createQueue("stream.file");
    OutputStream out = connection.createOutputStream(destination);

    // now write the file on to ActiveMQ
    byte[] buffer = new byte[1024];
    for (int bytesRead=0;bytesRead!=-1;) {
            bytesRead = in.read(buffer);
            System.out.println("bytes read="+bytesRead);
            if (bytesRead == -1) {
                out.close();
                System.out.println("Now existiong from prog");
                //System.exit(0);
                break;
            }
            else{
                System.out.println("sender\r\n");
                out.write(buffer, 0, bytesRead);
            }
    }
    System.out.println("After for loop");  
}
Run Code Online (Sandbox Code Playgroud)

当bytesRead == -1时,我想在JVM任务完成时从JVM卸载程序.为此,我最初使用了break关键字,并在Eclipse Console上生成以下输出

在此输入图像描述

使用此程序,程序不会从JVM卸载,因为控制台RED按钮仍处于活动状态.

现在我使用System.exit(0)来实现此目的,并从JVM退出程序.但我不想为此目的使用System.exit(0).我试图使用简单的虚空return代替break但它也无法正常工作.

请说明为什么breakreturn不在这种情况下工作结束程序以及为什么它仍在运行?

问候,

阿伦

Kay*_*man 5

您需要关闭资源(队列,输入流),因为它们可以使程序保持活动状态,之后简单的返回就足以结束程序.