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++;
}
}
}
Busy-waiting('while(true){...}')是一个非常糟糕的主意,因为这将占用100%或尽可能多的一个CPU,从而降低了工作线程的可用性。 – 2015-04-02 03:26:09
你还需要使'counter'变量'volatile'如下:'volatile int counter = 0;'。否则,不能保证你的主线程会在变量counter中看到变化。 – 2015-04-02 03:26:58
感谢反馈家伙,我决定改变我的实现,以传递工作线程应该在工作线程的构造函数中作为参数迭代的迭代值,以便不再需要检查。 – bakalolo 2015-04-02 04:43:53