多线程实现的二种方式


继承Thread

* 定义类继承Thread

* 重写run方法

* 把新线程要做的事写在run方法中

* 创建线程对象

* 开启新线程, 内部会自动执行run方法


public class Demo1_Thread {

    public static void main(String[] args) {

        MyThread mt = new MyThread(); //4,创建自定义类的对象

        mt.start(); //5,开启线程

        for(int i = 0; i < 3000; i++) {

            System.out.println("bb");

        }

    }

}

class MyThread extends Thread { //1,定义类继承Thread

public void run() { //2,重写run方法

    for(int i = 0; i < 3000; i++) { //3,将要执行的代码,写在run方法中

        System.out.println("aaaaaaaaaaa");

    }

}

}

实现Runnable

* 定义类实现Runnable接口

* 实现run方法

* 把新线程要做的事写在run方法中

* 创建自定义的Runnable的子类对象

* 创建Thread对象, 传入Runnable

* 调用start()开启新线程, 内部会自动调用Runnable的run()方法


public class Demo2_Runnable {

    public static void main(String[] args) {

        MyRunnable mr = new MyRunnable(); //4,创建自定义类对象

        Thread t = new Thread(mr); //5,将其当作参数传递给Thread的构造函数

        t.start(); //6,开启线程

        for(int i = 0; i < 3000; i++) {

            System.out.println("bb");

        }

    }

}

class MyRunnable implements Runnable { //1,自定义类实现Runnable接口

    public void run() { //2,重写run方法

        for(int i = 0; i < 3000; i++) { //3,将要执行的代码,写在run方法中

            System.out.println("aaaaaaaaaaaaaaaa");

        }

    }

}
原文地址:https://www.cnblogs.com/loaderman/p/6411125.html