2015-04-02 65 views
0

我正在尝试使用任意数量的工作线程来处理arraylist。我想跟踪每个工作线程处理了多少项目,并在特定数目后终止它们。会在工作线程类中声明一个变量counter并检查该计数器是否有效?线程中的访问变量

. 
. 
Thread t = new Thread(); 
t.start 
while(true){ 
if(t.counter >= 5){ 
    return; 
} 
} 
. 
. 

class Thread{ 
    int counter = 0; 
    public void run { 
     while(true){ 
     do something.... 
     counter++; 
     } 
    } 
} 
+0

Busy-waiting('while(true){...}')是一个非常糟糕的主意,因为这将占用100%或尽可能多的一个CPU,从而降低了工作线程的可用性。 – 2015-04-02 03:26:09

+0

你还需要使'counter'变量'volatile'如下:'volatile int counter = 0;'。否则,不能保证你的主线程会在变量counter中看到变化。 – 2015-04-02 03:26:58

+0

感谢反馈家伙,我决定改变我的实现,以传递工作线程应该在工作线程的构造函数中作为参数迭代的迭代值,以便不再需要检查。 – bakalolo 2015-04-02 04:43:53

回答

0

这是我会怎么做:

int counter = 0; 

Thread t = new Thread(new Runnable(){ 
    public void run { 
     while(true){ 
      doSomething... 
      counter++ 
     } 
    } 

}); 
t.start(); 

while(true){ 
    if(counter >= 5){ 
     return; 
    } 
} 

作为一个回答你的问题。我不知道有什么方法来访问运行的另一个线程的。可能有,但上面的代码会很好的工作。