多线程的创建方式1

  多线程的创建

方式一:继承于Thread类
  1.创建一个继承于Thread类的子类
  2.重写Thread类的run()方法-->将此线程执行的操作声明在run()方法中
  3.创建Thread类的子类的对象
  4.通过此对象调用start()方法

//例子:遍历100以内的所有的偶数

package com.atguigu.java;

//1.创建一个继承于Thread类的子类
class MyThread extends Thread {
    //2.重写Thread类的run()方法
    public void run(){
        for(int i=0;i<=100;i++){
            if(i%2==0){
                System.out.println(i);
            }
        }
    }
}

public class ThreadTest {
    public static void main(String[] args) {
        //3.创建Thread类的子类的对象
        MyThread t1=new MyThread();
        //4.通过此对象调用start()方法
        t1.start();

        for(int i=0;i<=100;i++){
            if(i%2==0){
                System.out.println(i+"*****main()******");//
            }
        }
    }
}

两条线程并行的时候,执行的顺序随机

两个备注:

  • start()的两个作用:causes this thread to begin execution; the Java Virtual Machine calls the run method of this thread

如果用t1.run(),就是在主线程中从上往下执行,并没有启动任何新线程

 

  • 一个线程里面最多只有一个start(),想要增加线程,就需要创建新的线程的对象

 

package com.atguigu.exer;

/**
 * 练习:创建两个分线程,其中一个线程遍历100以内的偶数,另一个遍历100以内的奇数
 */
class MyThread1 extends Thread{
    public void run(){
        for(int i=0;i<=100;i++){
            if(i%2==0){
                System.out.println(Thread.currentThread().getName()+":"+i);
            }
        }
    }
}

class MyThread2 extends Thread{
    @Override
    public void run() {
        for(int i=0;i<=100;i++){
            if(i%2!=0){
                System.out.println(Thread.currentThread().getName()+":"+i);
            }
        }
    }
}
public class ThreadDemo {
    public static void main(String[] args) {
        MyThread1 t1=new MyThread1();
        t1.start();
        MyThread2 t2=new MyThread2();
        t2.start();

还有更简洁的方法:

package com.atguigu.exer;

/**
 * 练习:创建两个分线程,其中一个线程遍历100以内的偶数,另一个遍历100以内的奇数
 */
public class ThreadDemo {
    public static void main(String[] args) {
        //创建Thread类的匿名子类的方式
        new Thread(){
            public void run() {
                for(int i=0;i<=100;i++){
                    if(i%2!=0){
                        System.out.println(Thread.currentThread().getName()+":"+i);
                    }
                }
            }
        }.start();

        new Thread(){
            public void run(){
                for(int i=0;i<=100;i++){
                    if(i%2==0){
                        System.out.println(Thread.currentThread().getName()+":"+i);
                    }
                }
            }
        }.start();
    }
}

 

posted @ 2022-04-15 10:52  SherryYuan  阅读(34)  评论(0)    收藏  举报