如何通过命令行覆盖Java Programm

时间:2015-10-27 10:37:01

标签: java xml ant build cmd

我写了一个并发的Mergesort代码,默认设置为5个线程,数组长度为1 000 000,我确保可以通过ant start从命令行启动应用程序。

现在我的问题是我还必须提供一个小命令行处理来通过控制台的命令参数覆盖最大线程数和数组长度。

问题是我该怎么做呢?为此,我需要编辑我的主代码或build.xml,或者只需要一个命令,比如转到main,更改这个和那个?

Main看起来像这样:

public class Main {

public static void main(String[] args) throws InterruptedException {

int nThreads=5;

int[] original = new int[1000000]; 
       for (int i=0; i<original.length; i++) {
        original[i] = (int) (Math.random()*9);
    }

    Mergesorts worker = new Mergesorts(original,nThreads);
    System.out.println("ressource: 1 of 5 thread(s) used");
    Thread w = new Thread(worker);
    w.start(); 
    w.join();

    }}

那就是我的build.xml文件:

<?xml version="1.0" encoding="UTF-8"?>


<project default="start" name="Mergesort-compile and run">

<target name="compile">
 <javac includeantruntime="false" srcdir="./src" destdir="Mergesort" />
</target>


<target name="start" depends="compile">
    <java classname="Main">
        <classpath path="Mergesort"/>
        </java>
</target>

1 个答案:

答案 0 :(得分:0)

检查以下代码:Java

public class Main {

  public static void main(String[] args) throws InterruptedException {
    int nThreads;

    if (args.length <= 0) {
      nThreads = 5;  // default number of threads
    } else {
      nThreads = Integer.parseInt(args[0]); // first passed parameter value 
    }

    int[] original = new int[1000000];
    for (int i = 0; i < original.length; i++) {
      original[i] = (int) (Math.random() * 9);
    }

    Mergesorts worker = new Mergesorts(original, nThreads);
    System.out.println("ressource: 1 of 5 thread(s) used");
    Thread w = new Thread(worker);
    w.start();
    w.join();

  }
}

Ant脚本:

<?xml version="1.0" encoding="UTF-8"?>


<project default="start" name="Mergesort-compile and run">

<target name="compile">
 <javac includeantruntime="false" srcdir="./src" destdir="Mergesort" />
</target>


<target name="start" depends="compile">
  <property name="nthread" value="5"/>

    <java classname="Main">
        <classpath path="Mergesort"/>
        <arg value="${nthread}" />
     </java>
</target>

将ant脚本运行为:

ant start -Dnthread=10 

这会将线程数设置为10