简体   繁体   English

Java和命令行参数中的线程

[英]Threads in Java and command line arguments

So I am writing a simple thread to add two vectors together and it takes 2 command line arguments: vector length and number of threads. 因此,我正在编写一个简单的线程来将两个向量相加,它需要2个命令行参数:向量长度和线程数。 From what I understand, the program is supposed to take in these two arguments and add up the vectors according to them showing the performance depending on the number of threads and vector length. 据我了解,该程序应该接受这两个参数,并根据它们相加向量,从而根据线程数和向量长度显示性能。 This is where I am stuck. 这就是我卡住的地方。 So far I have written basic code that adds two vectors together using arrays and creates the threads, showing the times but I am having trouble implementing it with the command line arguments. 到目前为止,我已经编写了基本的代码,该代码使用数组将两个向量相加并创建线程,显示了时间,但是我在使用命令行参数来实现它时遇到了麻烦。 Here is what I've done so far. 到目前为止,这是我所做的。

      public class Addition 
      {

         public static void main(String args[])
         {
        int NoOfThreads = Integer.parseInt(args[0]);
        VectorLength = Integer.parseInt(args[1]);

        System.out.println("Start time: " + System.nanoTime());//print start time
        Thread v1 = new Vector();
        Thread v2 = new Vector();
        Thread vsum = new Vector();


        //start all threads
        v1.start();    
        v2.start();    
        vsum.start();
        //vsum2.start();
        System.out.println("End time: " + System.nanoTime());//print end time
     }

  }

  public class Vector extends Thread
  {    


//create vectors and assign them arbitrary values
int v1[] = {12,13,14,15,16,17,18}; 
int v2[] = {15,19,20,22,24,26,28};

//initialise the vector sums to zero
int vsum = 0;
public void run()
{
        //loop to add up the elements of the first vector
        if(Integer.parseInt(args[0])> 0 )
        {
            for(int i = 0; i < v1.length; i++)
            {
                 for(int j=0; j<v2.length; j++)
                 {       
                    vsum = v1[i]+ v2[j];
                    System.out.println("Current total of vector 1: " + vsum);
                    try
                    {
                        System.out.println(System.nanoTime());
                        Thread.sleep(100);
                    }
                    catch (InterruptedException e)
                       {}           
                 }//for
            }

        }
}

} }

You cannot use args outside the main class. 您不能在main类之外使用args
Please don't use Vector as it is an implementation of ArrayList . 请不要使用Vector因为它是ArrayList的实现。
What you can do is add member variable to your thread class as int NoOfThreads and set it while constructing the thread class and use this in your run() . 您可以做的是将成员变量int NoOfThreads添加到thread类中,并在构造thread classint NoOfThreads进行设置,并在run()使用它。

A few notes: 一些注意事项:

  1. Your addition code uses a nested loop. 您的附加代码使用嵌套循环。 I assume that wasn't the intention. 我认为那不是意图。 In order to sum two vectors one loop is enough. 为了求和两个向量,一个循环就足够了。
  2. In main(..) , you are not waiting properly for the threads to terminate. main(..) ,您没有正确等待线程终止。 "End time:..." will be printed immediately after you start the threads. 启动线程后,将立即打印“结束时间:...”。 Use Thread.join() . 使用Thread.join()
  3. You are not using the number of threads in the input. 您没有在输入中使用线程数。 You always create and start 3 threads. 您总是创建并启动3个线程。 Same with the vector length. 与向量长度相同。 It's not passed down to the threads. 它没有传递给线程。
  4. Consider adding some unique id per thread, so that you can distinguish between them when they print to the console. 考虑为每个线程添加一些唯一的id,以便在它们打印到控制台时可以区分它们。
  5. As others mentioned, the code doesn't even compile. 正如其他人提到的那样,代码甚至无法编译。 Make it compile first ( vectorLength not declared, args unknown in the scope where it's used, etc.) 首先进行编译(未声明vectorLength ,在使用范围内args未知,等等)

I see two compilation problems here. 我在这里看到两个编译问题。

Firstly, the type of VectorLength isn't defined. 首先,没有定义VectorLength的类型。 I think it should be int VectorLength . 我认为应该是int VectorLength

Secondly, you are trying to access args reference in the Vector class which does not seem available. 其次,您尝试访问似乎不可用的Vector类中的args引用。

If you want to use args in the Vector class, you can pass this as an argument to Vector constructor and store it as a field. 如果要在Vector类中使用args ,则可以将其作为参数传递给Vector构造函数并将其存储为字段。 Something like this: 像这样:

public Vector(String[] args) {
    this.args = args;
}

And from your Addition class you should then be using this overloaded constructor: 然后从您的Addition类中,应该使用此重载的构造函数:

Thread v1 = new Vector(args);
Thread v2 = new Vector(args);

Creating a class as Vector will not be a problem since Vector is not a reserved keyword in Java and since you are not using the Vector Class of <>-><> it will not be a problem. 因为Vector不是Java中的保留关键字,所以将类创建为Vector将不会有问题,并且由于您没有使用<>-> <>的Vector类,因此不会有问题。

The only problem i can see is in this code 我唯一看到的问题是这段代码

int NoOfThreads = Integer.parseInt(args[0]);
VectorLength = Integer.parseInt(args[1]);

You are trying to initialize two variable NoOfThreads and VectorLength at the same time but have ended the statement in between with a semicolon. 您正在尝试同时初始化两个变量NoOfThreads和VectorLength,但是已经用分号结束了两者之间的语句。

int NoOfThreads = Integer.parseInt(args[0])**,**
    VectorLength = Integer.parseInt(args[1]);

notice the comma inplace of semicolon. 注意用逗号代替分号。

Secondly, you are trying to access args[0] in the run method in Vector class but the scope of args array is in the main method of the Addition. 其次,您尝试在Vector类的run方法中访问args [0],但args数组的范围在Addition的main方法中。

if(Integer.parseInt(args[0])> 0 )

Try solving both problems on your own. 尝试自己解决两个问题。 All the best. 祝一切顺利。

There are too many things broken in your code. 您的代码中有太多坏处。 Here are few. 这里有几个。

  1. You are using args outside of main. 您正在main之外使用args。 (set it as a attribute of Vector class and initialize it during object creation) (将其设置为Vector类的属性,并在创建对象时对其进行初始化)
  2. Vector works fine but it would make sense to use a different class name Vector可以正常工作,但是使用其他类名会很有意义
  3. You can have only one public class in a file. 文件中只能有一个公共类。 (Put Vector in a different file or remove public) (将Vector放在其他文件中或删除public)
  4. Why do you need the vector size and thread count from commmand line? 为什么需要从命令行开始的向量大小和线程数? Your vector size and tread count is static (pre-defined). 向量大小和踩踏数是静态的(预定义)。
  5. If you are trying to dynamically create a vector from the given size and also run threads from the thread size then there are lot of changes that needs to be made to your code. 如果您尝试根据给定的大小动态创建向量,并尝试根据线程大小运行线程,则需要对代码进行很多更改。

I would suggest to begin on more humble programming exercises before going for this task. 我建议在执行此任务之前先进行一些谦虚的编程练习。

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

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