Source: Xuetang online Tsinghua University advanced JAVA programming
Title Description:
Given several positive ints, the sum of the minimum prime factors of these positive integers is obtained. The minimum quality factor of 1 is 1.
In particular, the program requires to create a sub thread for each parameter, and find the minimum quality factor in the sub thread.
And add the quality factor to a specified variable.
The main thread will finally output the specified variable as a result.
The student's task is to complete the code of Result class, so that the whole program can be executed correctly.
Specifically, students need to correctly design the private member variables of the Result class and several public member methods. At the same time, the main goal of this topic is to pay attention to the correct use of synchronization mechanism.
This topic does not provide input and output samples. Please read the notes in the source code carefully.
Complete the code according to the notes.
package chapter02; import java.util.Scanner; class Result { //The student's task is to complete the Result class so that the whole program can run correctly. /***begin your code here***/ private int num; public Result(int num) { this.num = num; } synchronized public void addValue(int v) { this.num += v; } public int getValue() { return this.num; } /***end your code***/ } public class test01 { public static void main(String[] args) { //Generate input according to specified method int[] input = getInput(); //Define a Result instance to save the calculation results final Result result = new Result(0); //Parameters for each input //Using anonymous Thread and anonymous Runnable to create and execute a sub Thread for (final int n : input) { new Thread(new Runnable() { @Override public void run() { //If n is 1, the answer is 1. int t = 1; for (int i = 2; i != n + 1; ++i) if (0 == n % i) { t = i; break; } //T is the answer, add t to result result.addValue(t); } }).start(); } //The main thread does not do any synchronization with the sub thread for the time being. Simply wait for 300ms and output the result directly (this is of course caused by the hidden danger) try { Thread.sleep(300L); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(result.getValue()); } //This method is used to generate input parameters that students can ignore private static int[] getInput() { Scanner cin = new Scanner(System.in); int a = cin.nextInt(); int b = cin.nextInt(); int m = cin.nextInt(); int x = cin.nextInt(); cin.close(); int[] ret = new int[100]; for (int i = 0; i != 100; ++i) { x = (a * x + b) % m; ret[i] = x; } return ret; } }