Topic details:
7-1 2 Different Ways to Create Threads (25 points)
######There are two ways to create a thread. One is to inherit Thread to create a subclass, such as:
class sub_Thread extends Thread{
…
public void run() { //重写 run
…
}
}
Thread th = new sub_Thread (….);// 创建线程对象
Another implementation of Runnable, ######1. Create the target object class: implement the Runnable interface class
class target implements Runnable{
//实现Runnable接口 ,线程启动 执行run方法,可以共享 类里面的成员变量
public void run() { //重写
…..
}
}
2. Create a Thread thread object, the constructor Thread(Runnable target)
Thread th = new Thread(target);// Create a thread object
The programming implementation creates two threads, and the requirements are as follows: (1) One thread outputs the sum of 1 to n, and the other thread outputs the factorial of 1 to n. (2) One thread uses the writing method of the Thread subclass, and the other thread uses the writing method that implements the Runnable interface. There is an attribute int n in the thread class, there is a parameter construction method to assign value to n, and the run method is rewritten to realize the calculation and output the result ###### It is required to write a complete program to define the thread class
The main class prompt is as follows:
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int choice=sc.nextInt();
Thread th1=new math_thread(n);
target_thread tar=new target_thread(n);
Thread th2=new Thread(tar);
switch(choice) {
case 1:th1.start();break;
case 2:th2.start();break;
}
}
}
Input format:
Enter the value of n on line 1######Enter 1 or 2 on line 2
Output format:
If the input in the second line of the input format is 1, output the value of the summation ######If the input in the second line of the input format is 2, output the value of the factorial
Input sample:
A set of inputs is given here. E.g:
5
1
no blank line at the end
Sample output:
The corresponding output is given here. E.g:
15
no blank line at the end
Answer code:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int choice=sc.nextInt();
Thread th1=new math_thread(n);
target th2=new target(n);
Thread th = new Thread(th2);
switch(choice) {
case 1:th1.start();break;
case 2:th.start();break;
}
}
}
class math_thread extends Thread{
int n;
public math_thread(int n) {
this.n = n;
}
@Override
public void run() {
int sum=0;
for(int i = 1;i<=n;i++){
sum+=i;
}
System.out.println(sum);
}
}
class target implements Runnable{
int n;
public target(int n) {
this.n = n;
}
@Override
public void run() {
int sum=1;
for(int i=1;i<=n;i++){
sum=sum*i;
}
System.out.println(sum);
}
}