Experiment content and requirements
1. Purpose of the experiment
- Master Java multi-threaded programming methods.
2. Experimental content
Implement the following programs on the computer and observe the running conditions of the programs: - 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
Thread
class 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;
}
}
Runnable
interface 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();
}
}