实验内容及要求
一、实验目的
- 掌握Java多线程程序设计方法。
二、实验内容
上机实现下列程序并观察程序的运行情况: - 编写线程程序,在新线程中完成计算某个整数的阶乘。分别用Thread类和Runnable接口实现。
实验代码
Thread
类实现
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
接口实现
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();
}
}