Object-Oriented Programming (Java) Experiment 10

Experiment content and requirements

1. Purpose of the experiment

  1. Master Java multi-threaded programming methods.
    2. Experimental content
    Implement the following programs on the computer and observe the running conditions of the programs:
  2. Write a thread program to complete the calculation of the factorial of an integer in a new thread. Respectively use the Thread class and the Runnable interface to achieve.

experimental code

Threadclass implementation

package test10;
public class MyThread1 extends Thread{
    
    
    private int num;
    public void run(){
    
    
        int result = 1;
        for (int i=2;i<=num;i++){
    
    
            result *= i;
        }
        System.out.println(result);
    }
    MyThread1(int data){
    
    
        num = data;
    }
}

Runnableinterface implementation

package test10;

public class MyThread2 implements Runnable {
    
    
    private int value;
    MyThread2(int Value){
    
    
        value=Value;
        }
    public void start() {
    
    
        System.out.print(com(value));
    }
    public int com(int x){
    
    
        int result=1;
        for (int i = x; i > 1; i--) {
    
    
            result*=i;
            }
        return result;
    }
    @Override
    public void run() {
    
    
            throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }
}

验证主程序

package test10;
import java.util.Scanner;
public class mainAct {
    
    
    public static void main(String [] args) {
    
    
        Scanner input = new Scanner(System.in);
        MyThread1 one = new MyThread1(input.nextInt());
        one.run();

        MyThread2 two = new MyThread2(input.nextInt());
        two.start();

    }
}

insert image description here

Guess you like

Origin blog.csdn.net/qq_51594676/article/details/124995965