This thread program shows me different answers every time

风格不统一 提交于 2019-12-08 08:17:26

问题


This is a Java Program to Find The Number with Largest Divisors from 1-500000.

public class Medium2 {  
  static int  count1 = 1;  
  static int  count2 = 1;  
  static int  big_count = 0;  
  static int  big = 0;  

Main method

  public static void main(String[] args) {  
    Runnable runnable1 = new Runnable() {  
      public void run() {  

The implementation goes here

    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;  
    }  
  }  
};  

And the thread execution

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); 
  }  
}  

But it gives different answers every time. The actual answer is : 498960 and 200 Divisors


回答1:


Concerning your goal, your implementation should probably have problems. Since big_count and big is common for both threads and don't have any protection when threads are trying to modify those, your program should create errors.

Other than that, you are also not utilizing 2 threads, since both threads are doing calculation from 1 to 500000.

Since your calculation logic seems ok, you should get your desired output when you try with single thread.

If you want it to do by two threads, you can easily try this. (just to verify, not the nicest way)

  • You should have big_count1, big1 and big_count2, big2. So that variables whose names end with '1' is only using by thread1 and variables whose names end with '2' is only using by thread2.

  • Assign thread1 to check from 1 to 250000 and thread2 to from 250001 to 500000.

  • After join() s, just compare big_count1 and big_count2, then you can deduce the final answer. :))



来源:https://stackoverflow.com/questions/39956329/this-thread-program-shows-me-different-answers-every-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!