对问题的解释: 您必须编写一个多线程程序来查找所有 范围[1,n]中可被3、5或7整除的整数.返回 所有唯一整数的总和作为您的答案. 请注意,像15这样的整数(3和5的倍数)仅为 数过一次. 正整数n>;0作为输入提供给您.创建尽可能多的线程 你需要解决这个问题.您可以使用线程池获得加分.
Example:
Input: n = 10
Output: sum = 40
Explanation: Numbers in the range [1, 10] that are divisible by 3, 5, or 7 are:
3, 5, 6, 7, 9, 10. The sum of these numbers is 40.
我的解决方案和我面临的问题: 在这个程序中,我创建了三个线程,每个线程分别用于查找被3、5和7整除的整数,然后它将把它们全部存储在被除数数组列表中,并通过以下代码删除数组列表中的重复数:
Set<Integer> set = new HashSet<>(dividends);
dividends.clear();
dividends.addAll(set);
我使用了老师提供的一些测试用例,问题是在测试用例中,n=76293和n=1000不会显示预期的金额:
n=1000
expected sum:272066
actual sum:247377
另一个问题是,每次我运行测试用例时,实际金额都会不断变化. 有人能告诉我我的代码出了什么问题吗?我该如何修复它
我的代码是:
import java.util.*;
public class FindMultiples
{
public static ArrayList<Integer> dividends = new ArrayList<>();
public static int temp = 0;
public static synchronized void increment(){
dividends.add(temp);
}
public static class thread implements Runnable{
public int divisor;
public int n;
public thread(int n , int divisor){
this.n=n;
this.divisor=divisor;
}
@Override
public void run() {
for (int i=1 ; i<=n ; i++){
if (i%divisor==0){
temp=i;
increment();
}
}
}
}
public int getSum(int n) {
int sum = 0;
Thread thread1 = new Thread(new thread(n,3));
Thread thread2 = new Thread(new thread(n,7));
Thread thread3 = new Thread(new thread(n,5));
thread3.start();
thread2.start();
thread1.start();
try {
thread3.join();
thread2.join();
thread1.join();
}catch (InterruptedException e){
}
Set<Integer> set = new HashSet<>(dividends);
dividends.clear();
dividends.addAll(set);
for (int i : dividends){
sum+=i;
}
return sum;
}
public static void main(String[] args) {
}
}