Java 对于单线程/多线程,我如何调整它?

Java 对于单线程/多线程,我如何调整它?,java,multithreading,Java,Multithreading,我有一个类,基本上有两个方法,第一个方法采用文件和线程的字符串名称: public static void readFile(String s, Thread t){ Runnable read = new Runnable() { public void run() { //SOME CODE } t = new Thread(read); t.start(); } 第二个方法是一个主方法,它要求用户输入,然后使用该输入

我有一个类,基本上有两个方法,第一个方法采用文件和线程的字符串名称:

public static void readFile(String s, Thread t){
    Runnable read = new Runnable() {
      public void run() {
          //SOME CODE



}
        t = new Thread(read);
    t.start();

}
第二个方法是一个主方法,它要求用户输入,然后使用该输入设置一些事情,比如线程数是否只有一个,或者是否等于列表中的对象数

public static void main(String[] args){
  //SOME CODE

  for(Object x: ListOfObjects){
  //t1 is the same thread each time if one thread requested, otherwise t1 is a different thread each time
  readFromFile(textFileString, t1);
  //SOME CODE
}

如果用户要为列表中的5个项目请求5个线程,那么如何修改上述内容?目前,我的main方法有一个循环,用于计算列表中的项数,然后为循环中的每个迭代调用第一个方法。是否有一种方法可以获取用户请求的线程数,并在第一个方法中一次全部启动/启动它们,而不是一次一个并调用该方法?

实现Runnable接口。我试过了 这似乎是可行的:

class StringThread implements Runnable
{
    private String str;
    private int num;

    StringThread(String s, int n)
    {
        str  = new String (s);
        num =n; 
    }

    public void run ( )
    {
        for (int i=1; i<=num; i++)
            System.out.print ("THREAD NAMED: " + str+"  I IS: " +
                                               i + "\n"); 
    }
}

//IN the main program:

StringThread t1 = new StringThread ("THR-1",100);
new Thread(t1). start ( );    
StringThread t2 = new StringThread ("THR-2",200);
new Thread(t2). start ( );   

实现可运行接口。我试过了 这似乎是可行的:

class StringThread implements Runnable
{
    private String str;
    private int num;

    StringThread(String s, int n)
    {
        str  = new String (s);
        num =n; 
    }

    public void run ( )
    {
        for (int i=1; i<=num; i++)
            System.out.print ("THREAD NAMED: " + str+"  I IS: " +
                                               i + "\n"); 
    }
}

//IN the main program:

StringThread t1 = new StringThread ("THR-1",100);
new Thread(t1). start ( );    
StringThread t2 = new StringThread ("THR-2",200);
new Thread(t2). start ( );   

尝试用更具描述性的内容替换标题中的调整。Thread t参数在第一个方法中不是多余的吗?您正在使用它之前覆盖它。或者它是在某些代码中指定的?是的,现在我看到了,参数是多余的。请尝试用更具描述性的内容替换标题中的调整。在第一个方法中,Thread t参数不是多余的吗?您正在使用它之前覆盖它。或者它被分配到某个代码中?是的,现在我看到了,该参数是冗余的。没有理由在那里扩展线程。很少有。新字符串s应该做什么?构造函数中的语句str=new String s只是将类的字符串名称设置为输入字符串,以便线程可能被该字符串引用。没有理由在那里扩展线程很少有。新字符串s应该做什么?构造函数中的语句str=new String s只是将类的字符串名设置为输入字符串,以便线程可能被该字符串引用