在 Java 程序中多次执行 ProcessBuilder [英] Multiple execution of a ProcessBuilder in a Java program

查看:60
本文介绍了在 Java 程序中多次执行 ProcessBuilder的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 Java 程序中使用 ProcessBuilder,该程序将在同一程序中多次使用.为数据库中的每条记录检查此代码片段.如果只有一条记录满足开始时间/结束时间等约束,那么我没有任何问题,但是如果两条记录满足这些约束中的任何一个,那么第一条记录,它会执行 processbuilder 中的命令并将输出重定向到日志文件.记录但第二条记录,它不会执行 processbuilder 中的命令并将输出重定向到相同的日志文件.在这个网站上有一个关于这个问题的类似问题,但在下面的链接中没有得到回答.我希望至少现在有人能解决这个问题并给我们一个解决方案.我真的不明白我哪里做错了.任何对这个概念有想法的人请回复这个问题,让我知道我做错了什么.

I want to use ProcessBuilder in a Java program which will be used many times in the same program. This code snippet is checked for every record in the database. If only one record satisfies the constraints like start time/end time then I don't have any problem, but if two records satisfies any of these constraints then first record, it executes the commands in the processbuilder and redirects output to logfile. Log but the second record, it doesn't executes the commands in the processbuilder and redirects output to the same logfile. There is a similar question about this problem in this site which has not been answered in the below link. I hope that atleast now anyone will go through this issue and give us a solution. I really don't understand where I am doing it wrong. Anyone who has idea about this concept please reply to this question and let me know where I am doing wrong.

一个程序中的多个进程构建器

while(rs1.next())
        {
            instance_id = rs1.getString(1);
            startdate = rs1.getString(2);
            starttime = rs1.getString(3);
            endtime = rs1.getString(4);
            enddate = rs1.getString(5);
            if(presentdate.equals(startdate) || presentdate.equals(enddate))
            {
                if(presenttime.equals(starttime))
                {
                    String[] s1 = new String[]{"cmd", "/c","ec2-start-instances",instance_id,">>","D:\\logfile.log"};
                    ProcessBuilder builder1 = new ProcessBuilder(s1);
                    Process p1 = builder1.start();
                }
                else if(presenttime.equals(endtime))
                {
                    String[] s1 = new String[]{"cmd", "/c","ec2-stop-instances",instance_id,">>","D:\\logfile.log"};
                    ProcessBuilder builder1 = new ProcessBuilder(s1);
                    Process p1 = builder1.start();
                }
            }
        }

推荐答案

我建议你使用

p1.waitFor();

在启动另一个线程之前将此线程与子进程同步,尤其是当它们具有共同的资源 (D:\logfile.log) 时.

to sync this thread with the subprocess before starting another one, especially when they have a resource (D:\logfile.log) in common.

这篇关于在 Java 程序中多次执行 ProcessBuilder的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆