软件应该做一些计算:总共 62500 个循环,一个循环持续时间是 0.5 秒。那将是大约 8 小时的工作(for in for in for)。我必须分成 100 个单独的线程,工作时间将减少到 8 分钟。我无法打开 62500 个线程,因为 CPU,我必须找到仅打开 100 个线程而不是再次打开 100 个线程的解决方案。我尝试使用 CountDownLatch 但我无法重置循环,所以我的解决方案是 CyclicBarrier。
private CycleBarrier cb;
// this Overrided run is called only once from the view to not block the UI.
@Override
public void run(){
// count is the number of the actions that i want to do
// this is why I'm using CycleBarrier
for(int count = 0; count < 2; count++){
System.out.println("MAIN THREAD: #"+count);
int x1 = 0;
cb = new CycleBarrier(100, new Runnable(){
@Override
public void run(){
// HOW TO STOP CYCLE ???
}
});
for(int i = 0; i < 100; i++){
new Thread(new Test(x1, cb)).start();
x1 += 25;
}
}
}
和测试类
public class Test implements Runnable{
int x1;
CycleBarrier cb;
public Test(int _x1, CycleBarrier _cb){
x1 = _x1;
cb = _cb;
}
@Override
public void run(){
// this for in for has 6250 loops
for(int i = x1; < x1+25; i++){
for(int j = 0; j < 250; j++){
System.out.println(" |--> LOOK I'm WORKING: "+i+" "+j);
}
}
// After the job is done, it should be put in to await
cb.await();
}
}
循环不工作。一下子开200个。我尝试调试(eclipse)但我不知道为什么,线程从一个跳到另一个,我无法跟踪结果。
控制台应如下所示:
MAIN THREAD: #0
LOOK I'm WORKING: 0 0
LOOK I'm WORKING: 0 1
...
LOOK I'm WORKING: 25 254
LOOK I'm WORKING: 25 255
MAIN THREAD: #1
LOOK I'm WORKING: 0 0
LOOK I'm WORKING: 0 1
...
LOOK I'm WORKING: 25 254
LOOK I'm WORKING: 25 255