Thread Job: java implements multithreaded co-computing of quadratic equations of one variable

Keywords: Java less

;

The school teacher set up two small threading jobs

1. Design aTest.cpp, defines variables: unsigned int sum=0; creates two threads T1 and T2, T1 behavior: sum+=1; T2 behavior: sum+=2; when the sum is greater than 1000000, outputs the sum value and ends the program.
Q1: Run the program 10 times and record the results.
Q2:10 run results are consistent?If not, explain the reason.
Q3: Design anotherAutorun.cppIt canTest.exeRun N times (n=10000 or 100000...), automatically collect run results and save them inResult.txtFile.
Q4: Can we eliminateTest.exeInconsistency of results over multiple runs?Please give a solution and test its feasibility.

2. Design aQuadratic.cppFor solving N (n=10000 or 100000...)The coefficients a, b and c of the univariate quadratic equation are random integers, where a_0.takeQuadratic.cpp Multithreading2.cpp was modified to solve univariate quadratic equations with two threads.
Q1:Calculate separatelyQuadratic.cppRuntime with Multithreading2.cpp.
Q2: Calculate the Multithreading2.cpp acceleration ratio.
Q3: The difficulties in parallelizing serial algorithms are analyzed and summarized.
Q4: Retrieve the mainstream technologies, architectures and platforms that support parallel computing and describe their characteristics.

================================================================================
The teacher intended that it would be best to write in c, but at that time he had not sent out such detailed assignments.When I found my teacher's hair halfway through the writing, I had to put my scalp on it.

If available, c's code will be added.

================================================================================
The source code is as follows

================================================================================
Q1:
1. Create two threads, each implementing different functions.

package com.example.aosdemo.homework1;
/**
 * Anonymous Thread Class
 *
 * @author _Yuan
 * @since 2020-6-15 18:40:15
 */
public class Test {
   public static int sum=0;
   public  void runAll(){
       Thread thread1 = new Thread(){
           public void run(){
               while(sum<=1000000){
                   sum+=1;//Add 1 at a time
               }
               System.out.println("Thread1: sum="+sum);
           }
       };
       //Thread 2
       Thread thread2 = new Thread(){
           public void run(){
               while(sum<=1000000){
                   sum+=2;//Add 2 at a time
               }
               System.out.println("Thread2: sum="+sum);
           }
       };
thread1.start();
       thread2.start();
   }
 public static void main(String[] args) {
        Test test = new Test();
        test.runAll();
  }
}
}

Run result:
The results of each run are not exactly the same, sometimes the same, sometimes different.And the execution order is different.
Reason:
When the same data is accessed between multiple threads, the threads are in a competitive state, and whoever gets it first runs one time slice, and then grabs it the next time slice, so the result is not unique.




2. Execute the above procedure N times and save the execution result in txt.

package com.example.aosdemo.homework1;
import java.io.FileNotFoundException;
import java.io.PrintStream;
/**
 * Anonymous Thread Class
 *
 * @author _Yuan
 * @since 2020-6-16 16:31:21
 */
public class Autorun {
 public static final int NUM = 10000;
    public void wite() {
        try {
            PrintStream ps = new PrintStream("e:/result.txt"); // Creates a printout stream whose output goal is:Result.txtfile
            System.setOut(ps);//Assign the created printout stream to the system.That is, the next time the system outputs to ps
            //Loop Execution
            for (int i = 0; i <NUM ; i++) {
                Test test = new Test();
                test.runAll();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            System.out.close();
        }
}

Run result:
The results are unstable and some of the results are inconsistent.

3. To solve the above problem, I use a thread pool to perform all tasks serially.That is, to ensure that all tasks are executed in the order in which they are submitted.

package com.example.aosdemo.homework1;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
 * Thread pool SingleThreadExecutor causes thread sequential execution
 *
 * @author _Yuan
 * @since 2020-6-16 21:42:35
 */
public class ThreadPoolTest {
    public static int sum = 0;
    static ExecutorService executorService = Executors.newSingleThreadExecutor();
    public static void main(String[] args) {
        final Thread thread1 = new Thread(new Runnable() {
            @Override
            public void run() {
                while (sum <= 1000000) {
                    sum += 1;//Add 1 at a time
                }
                System.out.println("Thread1: sum=" + sum);
            }
        }
        );
        final Thread thread2 = new Thread(new Runnable() {
            @Override
            public void run() {
                while (sum <= 1000000) {
                    sum += 2;//Add 2 at a time
                }
                System.out.println("Thread2: sum=" + sum);
            }
        }
        );
        executorService.submit(thread1);//Thread pool commit
        executorService.submit(thread2);
        executorService.shutdown();//Close thread pool, reject task
    }
}

Run result:
The execution results are consistently 1000001, and the execution order is always Thread1, Thread2.



note:
I don't know a solution, so take a look at this article----. Eight ways to make threads execute sequentially

================================================================================
Q2:
1. Write a loop to solve n univariate quadratic equations and add code to calculate run time.Encapsulated in the same thread class.

package com.example.aosdemo.homework2;
import java.util.Random;
/**
 * Thread class: calculates NUM univariate quadratic equations
 * *note: It is normal to have decimals in the results. If you want more accurate results, you can use BIgDecimal (for addition, subtraction, multiplication and division of the double type).
 * @author _Yuan
 * @since 2020-6-14 18:32:13
 */
public class Mythread implements Runnable {
    public static final int NUM = 10001;//Number of equations
    public static int count1;//count
    public static int count2;
    @Override
    public void run() {
        long startTime = System.currentTimeMillis();    //Get Start Time
        Random random = new Random(100);//The random numbers generated by the same number of times are the same, so it must be written outside the for loop that NUM=100010 is the seed and NUM=10000 when 100 is the seed.
        for (int i = 1; i < NUM; i++) {
//            try {
//                Thread.sleep(1); //Sleep 2ms, modified to a certain value, allows multiple threads to work together when processing tasks account for a more even proportion
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
            task(i, random);
        }
        long endTime = System.currentTimeMillis();    //Get End Time
        System.out.println("The total time spent in the program is:" + (endTime - startTime) + "ms");    //Output Program Runtime
        //Determine if it's single-threaded or multi-threaded
        if ("singleThread".equals(Thread.currentThread().getName())) {
            System.out.println("singleThread Number of processing tasks:" + (count1 + count2));
        } else {
            System.out.println("multiThread1 Number of processing tasks:" + count1 + " multiThread2 Number of processing tasks:" + count2);
        }
    }
    //Calculating Quadratic Univariate Equation
    public void task(int i, Random random) {
//    Solution: x1,x2 random parameters: a,b,c criteria:t
        int a = random.nextInt(100);//Returns a random number greater than or equal to 0 and less than 100
        int b = random.nextInt(100);
        int c = random.nextInt(100);
        double x1, x2, t;
        t = b * b - 4 * a * c;//Determine if there are solution conditions
        if (a != 0) {
            if (t < 0) {
                System.out.println("equation set" + i + ": " + a + "X*X+" + b + "X+" + c + " unsolvable " + " By " + Thread.currentThread().getName());
                count1++;
            } else {
                x1 = ((-b) + Math.pow(t, 1 / 2)) / (2 * a);
                x2 = ((-b) - Math.pow(t, 1 / 2)) / (2 * a);
                System.out.println("equation set" + i + ": " + a + "X*X+" + b + "X+" + c + " Solve as-->X1=" + x1 + "," + "X2=" + x2 + "  " + " By " + Thread.currentThread().getName());
                count2++;
            }
        }
    }
}

2. Create a single thread and execute the run method.

package com.example.aosdemo.homework2;
/**
 * Comparison: Single-threaded quadratic equation
 * @author _Yuan
 * @since 2020-6-15 00:45:05
 */
public class Quadratic {
    public static void main(String[] args) {
        //Single Thread
        Mythread singleThread = new Mythread();
        new Thread(singleThread,"singleThread").start();
    }
}

Execution results:

3. Create a thread class object, which is used by both threads, and run the run method to achieve a coordinated solution for the threads.

package com.example.aosdemo.homework2;
/**
 * Comparison: Multithreaded co-computing of quadratic equation of one variable
 * note: Since the equation parameters for each execution are generated by random numbers, all unavoidable calculations differ from one another, sometimes with a single thread taking less time
 * @author _Yuan
 * @since 2020-6-15 00:45:05
 */
public class Multithreading2 {
    public static void main(String[] args) {
        //Collaborative multithreading
        Mythread multiThread = new Mythread();
        new Thread(multiThread,"multiThread1").start();
        new Thread(multiThread,"multiThread2").start();
 }
}

Execution results:

Posted by landonmkelsey on Tue, 16 Jun 2020 09:42:00 -0700