1
这是一个Java程序,可从1-500000查找具有最大除数的数字。此线程程序每次向我显示不同的答案
public class Medium2 {
static int count1 = 1;
static int count2 = 1;
static int big_count = 0;
static int big = 0;
主要方法
public static void main(String[] args) {
Runnable runnable1 = new Runnable() {
public void run() {
实现放在这里
for (int num = 1; num <= 500000; num++) {
for (int i = 2; i <= num; i++) {
if (num % i == 0) { //Actual Logic
count1++;
}
}
if (count1 > big_count) {
big_count = count1; //Number of Divisors
big = num; //Largest Number
}
count1 = 1;
}
}
};
和线程执行
Thread thread1 = new Thread(runnable1); //Threads
Thread thread2 = new Thread(runnable1);
thread1.start();
thread2.start();
try {
thread1.join();
thread2.join();
} catch (InterruptedException ie) {
;
}
System.out.println("Biggest: " + big + "\nNumber of Divisors for " + big + " = " + big_count);
}
}
但它给不同的答案每次。实际答案是:498960和200除数
“实际的答案是:”......不,它不是。实际的答案取决于运行,而不取决于你的想法。你会得到不同的结果,因为每次都有不同的结果 – Stultuske
“but”从哪里来?你的程序在数据竞赛中是膝下的。 –
线程在不同运行时会给出不同的结果 –