实现多线程的两种方式

1.继承Thread类。

源码结构:public class Thread implements Runnable

从中可以看出Thread类实现了Runnable,由于java中不支持多继承,所以实现多线程时,可以采用实现Runnable的方式。

2.实现Runnable接口。

注意一下声明与调用不仅仅只是new一下,start一下,而是new两下,start一下:

public class MyRunnable implements Runnable {
    public void run() {
        System.out.println("运行中!");
    }
}
public class MainTest {

    public static void main(String[] args) {
        Runnable runnable = new MyRunnable();
        Thread thread = new Thread(runnable);
        thread.start();
    //    runnable.run();这种调用不会启动线程,只是单纯的方法调用
        System.out.println("运行结束!");
    }

}
原文地址:https://www.cnblogs.com/cing/p/8933519.html