JAVA程序设计进阶(自主模式)-通过RUNNABLE接口创建线程

版权声明:文章都是原创,转载请注明~~~~ https://blog.csdn.net/SourDumplings/article/details/88934365

通过RUNNABLE接口创建线程

(100/100 分数)

题目描述

设计并实现一个MyRunnable类,要求该类实现Runnable接口。

MyRunnable类具有一个int类型的私有成员,由构造器传入。

在实现Runnable接口覆写run方法中,计算并输出该私有成员的阶乘。

主方法将会根据输入创建MyRunnable的实例,并利用该实例创建Thread实例从而在新的子线程中计算输出给定输入的阶乘。

学员可以注意本题中创建线程的方法与1.2节中题目的区别。

学员无需实现主方法,只需按照指示补全MyRunnable类即可。

本题中出现的所有数据均在int范围之内。

本题不提供输入输出样例

Java:

import java.util.*;
public class Main{
    public static void main(String [] args){
        Scanner cin = new Scanner(System.in);
        int n = cin.nextInt();
        cin.close();

        //利用MyRunnable实例创建一个Thread实例
        //并且在新的线程中执行
        new Thread(new MyRunnable(n)).start();
        System.out.println("Main thread ends.");        
    }
}
class MyRunnable implements Runnable{
    private int num;//私有成员
    //在以下实现MyRunnable的构造方法以及覆写run方法
    /***begin your code here***/
    public MyRunnable(int n)
    {
    	this.num = n;
    }
    
    public void run()
    {
    	int res = 1;
    	int i;
    	for (i = num; i > 0; --i)
    		res *= i;
    	System.out.println(res);
    	return;
    }


    /***end your code***/
}

猜你喜欢

转载自blog.csdn.net/SourDumplings/article/details/88934365