繁体   English   中英

暂停main方法中循环的执行,直到所有线程完成Java 1.5

[英]Pause execution of a loop in main method till all Threads finish Java 1.5

我正在使用Java 1.5从命令行读取多个参数。 参数是平面文件的名称。 我循环遍历main方法中的参数,然后调用一个方法,该方法又创建了一堆线程来处理文件。 我需要暂停循环,直到所有处理第一个参数的线程完成,然后继续为第二个参数创建线程。 如何在我的main方法中将参数排队或暂停循环执行,直到所有处理当前参数的线程完成?

使用线程池和执行程序。 看一看java.util.concurrent包。

for(String argument:args){
  //you said you want multiple threads to work on a single argument.
  //create callables instead and use a ThreadPool
  List<Callable<YourResult>> lstCallables = createCallablesFor(argument);
  List<Future<YourResult>> futures = Executors.newCachedThreadPool().invokeAll(lstCallables);
  for(Future<YourResult> future:futures){
    //this get() waits until the thread behind the current future is done.
    // it also returns whatever your callable might return.
    future.get(); 
  }
  // at this point, all the threads working on the current argument are finished
  // and the next loop iteration works on the next argument
}

我想知道您是否正在寻找周期性障碍之类的东西。

您需要为一个参数在循环内启动线程作业,以便在完成一个作业后启动下一个循环并为下一个参数启动下一个线程作业。 而且,您可以在定义该线程的线程工作中工作。

示例:这只是一个片段

for (int i = 0; i < count; i++) {
    t[i] = new RunDemo();
    String[] serverList = srv[i].split(",");
    String logName = filename + "_" + serverList[0] + "_log";
    String sql = "INSERT INTO .....(any query)";
    t[i].setStr("sqlplus -L " + username[i] + "/" + password[i] + "@"
                + serverList[1] + ":" + serverList[2] + "/" + serverList[3]
                + " @" + filename1);
    t[i].setLogName(logName);
    t[i].setDirectory(dir);
    try{
        conn.UpdateQuery(sql);
        log.info("Inserted into the table data with query " + sql);
    }
    catch (Exception e){
        log.info("The data can't be inserted into table with " + e.getMessage() + " sql query " + sql);
    }
    new Thread(t[i]).start();
}

在每个循环中,将创建并启动具有不同serverList的新线程。

现在,工作定义如下:

public void run() {
    JShell jshell = new JShell();
    try {
        log.info("Command is: " + this.str + " log name: " + this.LogName + " in directory: " + this.directory);
        jshell.executeCommand(this.str, this.LogName, this.directory);
        log.info("Executed command successfully");
    } catch (Exception e1) {
        log.info("Error at executing command with error stack: ");
        e1.printStackTrace();
    }
    DBConnection conn1 = new DBConnection();
    String sql = "UPDATE patcheventlog SET ENDTIME=SYSDATE WHERE LOGFILE='" + this.directory + this.LogName + "'";
    try {
        //conn1.callConnection("192.168.8.81", "d2he");

        conn1.callConnection(ip, sid);

        conn1.UpdateQuery(sql);
        conn1.disposeConnection();
    } catch (SQLException e) {
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }
    System.out.print(this.LogName);
}

因此,这就是处理循环内线程的方式。 您无需暂停循环。

希望能有所帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM