Java多线程:分散复杂的工作负载



我必须创建一个性能至关重要的统计应用程序。简而言之:

  • 我的应用程序收到一系列数字(例如50.000-150.000(-该范围可以不断变化
  • 对于范围内的每个号码,应用程序应执行网络请求和各种检查
  • 有些数字需要检查两次甚至更频繁,有些只检查一次,有些根本不检查

遗憾的是,我对编程还很陌生,而且还在学习——所以这就是我目前正在做的事情(请注意,为了简单起见,有些部分是伪代码(:


1:将范围划分为100个部分,这样每个线程都有自己的范围来检查(使用了100个线程(

ArrayList<String> FetchingRanges = new ArrayList<>();
int totalRangeToFetch = rangeStart - rangeEnd; //amount of numbers to check (100.000 in this example)
int rangePerThread = totalRangeToFetch / 100; //Range per thread (10.000 numbers per thread in this example)
int rangeCounter = rangeStart; //this defines the starting point for the loop
for (int i = 0; i < 100; i++) {
int FROM = rangeCounter;
rangeCounter+= rangePerThread;
int TO = rangeCounter;
rangeCounter++;
FetchingRanges.add(FROM + ";" + TO);
}

2:这给了我一个ArrayList";FetchingRanges;充满部分范围,例如

FetchingRanges.get(0) -> 50000;60000 //This is what the first thread has to check
FetchingRanges.get(1) -> 60001;70000
//...
FetchingRanges.get(99) -> 140001;150000 //This is what the last thread has to check

3:接下来,我将启动100个线程,每个线程检查其编号:

for (int i = 0; i < 200; i++) {
new Thread() {
@Override
public void run() {
int Start = Integer.parseInt(FetchingRanges.get(i).split(";")[0]);
int End = Integer.parseInt(FetchingRanges.get(i).split(";")[0]);
for (i = Start; i <= End; i++){
//... Check Number, Do Network Request, Analyze and Report
}
}
}.start();
}

这个解决方案的问题很简单:我希望所有线程都有相等的负载,但由于有些数字比其他数字更难检查,一些线程只是在空闲,等待下一个范围(可能在几分钟内(,而另一方面,一些线程仍在工作,直到需要检查下一个区域才能完成工作。

提前感谢您的帮助!

感谢您在评论中的帮助,我找到了ThreadPools的最佳解决方案。线程没有必要将范围划分为更小的部分,总的来说,性能似乎是惊人的。这就是我所做的:

public static ExecutorService MyExecutor = Executors.newFixedThreadPool(50);
for (int j = Start; j <= End; j++) {
MyExecutor.execute(new Runnable(){...});
}

最新更新