2011-06-27 37 views
1

線程我需要知道Java線程的陣列。這裏是C#陣列在Java中

Thread[] TCreate = new Thread[iThreadSize]; 
     for (int i = 0; i < TCreate.Length; i++) 
     { 
      TCreate[i] = new Thread(delegate() 
       { 
        lst.Add(this.getResult(url)); 
       }); 
      TCreate[i].Name = "URL"+i; 
      TCreate[i].Start(); 

     } 
     for(int j=0;j<TCreate.Length;j++) 
      while (TCreate[j].IsAlive) 
      Thread.Sleep(10); 

我需要知道要做到這一點在Java線程的陣列碼。

MyTestClass qryCompoents=new MyTestClass(); 
for(int i=0;i<ThreadSize;i++) 
     { 

      switch(obj.getQueryLevelValue(i)) //Decide according to level 
      { 
      case 1: 
        qryCompoents.prepareAndProcess_I(obj.getQueryString(i),obj,i); 
        break; 
      case 2: 
        qryCompoents.prepareAndProcess_II(obj.getQueryString(i),obj,i); 
        break; 

      }    

     } 

讓我知道你是否需要任何細節。

如果我轉換此

Thread[] TCreate = new Thread[numExpression]; 

     for(int i=0;i<numExpression;i++) 
     { 
      TCreate[i] = new Thread(new Runnable() { 
        public void run() { 
         switch(obj.getQueryLevelValue(i)) //Decide according to level 
         { 
         case 1: 
           qryCompoents.prepareAndProcess_I(obj.getQueryString(i),obj,i); 
           break; 
         case 2: 
           qryCompoents.prepareAndProcess_II(obj.getQueryString(i),obj,i); 
           break; 

         }   
        } 
       }); 
       TCreate[i].setName("URL"+i); 
       TCreate[i].start();   
     } 
      for (int j = 0; j < TCreate.length; j++) 
       while (TCreate[j].isAlive()) 
        Thread.sleep(5); 

顯示錯誤:無法指非最終變量「OBJ」在不同的方法中定義的內部類內部

由於事先

+0

任何人都可以幫我.. –

+0

'obj'的聲明是怎麼樣的? (我更新了我的答案) – dacwe

回答

5

它非常類似。 java代碼有一個Runnable接口,而不是C#s Name屬性java有setName方法。除此之外的差異是次要的:

Thread[] TCreate = new Thread[iThreadSize]; 
for (int i = 0; i < TCreate.length; i++) { 

    TCreate[i] = new Thread(new Runnable() { 
     public void run() { 
      lst.Add(this.getResult(url)); 
     } 
    }); 
    TCreate[i].setName("URL"+i); 
    TCreate[i].start(); 
} 

for (int j = 0; j < TCreate.length; j++) 
    while (TCreate[j].isAlive()) 
     Thread.sleep(10); 

至於你obj變量,我不知道它是什麼,你可以嘗試把它聲明final但請注意,final引用無法更改,但在您的情況下它可能正常工作。

`final Object obj = ....;` 
+0

感謝很多它工作正常.... –

1

注意,你也可以用這個來得到一個組的所有活動的線程:

​​3210
2

使用線程池,你會做以下。

// only needed if you don't want to reuse the pool. 
ExecutorService executor = Executors.newCachedThreadPool(); 

// ---- 
List<Future<Result>> results = new ArrayList<Future<Result>>(); 
for (int i = 0; i < iThreadSize; i++) 
    results.add(executor.submit(new Callable<Result>() { 
     public Result call() { 
      return getResult(url)); 
     } 
    }); 

for(Future<Result> future: results) 
    lst.add(future.get()); 
// ---- 

// only needed if you don't want to reuse the pool. 
executor.shutdown();