JAVA程序设计进阶(自主模式)-通过匿名Thread与匿名Runnable创建线程

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

 

(100/100 分数)

题目描述

在第一个编程作业中我们通过继承Thread创建了一个MyThread对象,并通过MyThread的一个实例来执行线程。

在第二个编程作业中我们通过实现Runnable接口创建了一个MyRunnable对象,并使用MyRunnable的一个实例作为参数创建了一个Thread的实例。

本作业则直接使用Thread与Runnable的匿名对象来创建线程。

线程需要完成的任务仍然是计算并输出给定参数的阶乘。

在整个程序中既不会出现MyThread也不会出现MyRunnable,我们只需要关注实现本身,而不必费尽心思考虑名字。

另外提醒学员注意观察一下子线程如何与主线程共享数据,提示:使用final变量

本题不提供输入输出样例,请仔细阅读源代码中的注释。

按照注释要求补全代码。

Java:

import java.util.*;
import java.util.Scanner;

public class Main{
    
	public static void main(String[]args) {	
		//输入一个整数
		Scanner cin = new Scanner(System.in);
		final int n = cin.nextInt(); // 声明final才能在内部类中使用
		cin.close();
		
		//书写代码创建一个线程来计算并输出阶乘
		//不要额外定义类,只使用Thread与Runnable即可
		/***begin your code here***/
		
		new Thread(new Runnable()
		{
			@Override
			public void run()
			{
				int res = 1;
				for (int i = n; i > 0; --i)
					res *= i;
				System.out.println(res);
			}
		}).start();

		/***end your code***/
		//标记主线程结束
		System.out.println("Main thread ends.");		
		return;
	}

}

猜你喜欢

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