2

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

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 方法有一个循环(用于列表中的项目数),然后为循环中的每次迭代调用第一个方法。有没有办法获取用户请求的线程数,并在第一个方法中一次性启动/启动它们,而不是一次一个并调用该方法?

4

1 回答 1

0

实现 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 ( );   
于 2012-04-30T22:03:18.070 回答