简体   繁体   English

如何通过命令行覆盖Java程序

[英]How to overwrite Java Programm via Command Line

I wrote a concurrent Mergesort code with the default setting of 5 threads and an array length of 1 000 000 and i made sure that the aplication can be started from the command line via ant start. 我编写了一个并发的Mergesort代码,默认设置为5个线程,数组长度为1 000 000,并且确保可以通过ant start从命令行启动应用程序。

Now my problem is that i also have to provide a small command line handling to overwrite the maximum thread number and the array length via command parameters from the console. 现在我的问题是,我还必须提供一个小的命令行处理程序,以通过控制台中的命令参数覆盖最大线程数和数组长度。

The Question is how can i do that and for that do i need to edit my Main code or the build.xml or just a command like go to main, change this and that ? 问题是我该怎么做,为此,我需要编辑我的Main代码或build.xml或只是一个命令,例如转到main,更改此内容和那个?

Main looks like this: 主要看起来像这样:

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();

    }}

and thats my build.xml file: 那就是我的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>

Check bellow code : Java 检查下面的代码: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 Script : 蚂蚁脚本

<?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>

Run ant script as : 运行ant脚本为:

ant start -Dnthread=10 

this will set number of threads as 10 这会将线程数设置为10

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

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