实现多线程的两种方式

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("运行结束!");
    }

}

 

posted on 2018-04-24 20:33  二十年后20  阅读(111)  评论(0编辑  收藏  举报

导航