多线程实现方法1:
继承Thread类
步骤:
①继承Thread类
②重写run()方法
③创建继承类的对象
④通过继承类对象实现start()方法
举例:
/**
* 创建多线程方式1:继承Thread类
* 1.创建一个继承Thread类的子类
* 2.重写Thread类的run()方法
* 3.创建子类的对象
* 4.通过子类调用start()方法
* @author Dionysus_xu
* @create 2022-02-25-12:46
*/
public class MultiThread{
public static void main(String[] args) {
Thread1 t1 = new Thread1();
t1.start();
Thread2 t2 = new Thread2();
t2.start();
Thread3 t3 = new Thread3();
t3.start();
}
}
class Thread1 extends Thread{
//线程1:计算1-100的值
@Override
public void run() {
int sum = 0;
for(int i = 1;i<=100;i++){
sum+=i;
}
System.out.println("线程1:");
System.out.println("1-100的结果为:"+"\n"+sum);
}
}
class Thread2 extends Thread{
//线程2:输出100以内的平方数
@Override
public void run() {
System.out.println("线程2:");
System.out.println("100以内的平方数有:");
for(int i = 0;i<100;i++){
for(int j =0;j<Math.sqrt(100);j++){
if(i == j*j){
System.out.println(i+"="+j+"²");
}
}
}
}
}
class Thread3 extends Thread{
//线程3:没啥好说的了
@Override
public void run() {
System.out.println("线程3:");
System.out.println("简单run一run吧");
}
}