Java中建立线程有两种方法,一种是继承Thread类,另一种是实现Runnable接口,并通过Thread和实现Runnable的类来建立线 程,其实这两种方法从本质上说是一种方法,即都是通过Thread类来建立线程,并运行run方法的。

    但它们的大区别是通过继承Thread类来建立线程,虽然在实现起来更容易,但由于Java不支持多继承,因此,这个线程类如果继承了Thread,就不能再继承其他的类了,因此,Java线程模型提供 了通过实现Runnable接口的方法来建立线程,这样线程类可以在必要的时候继承和业务有关的类,而不是Thread类

 

    实现Runnable接口的类必须使用Thread类的实例才能创建线程。通过Runnable接口创建线程分为两步:

    1. 将实现Runnable接口的类实例化。

    2. 建立一个Thread对象,并将第一步实例化后的对象作为参数传入Thread类的构造方法。

package mythread;

public class MyRunnable implements Runnable
{
    public void run()
    {
        System.out.println(Thread.currentThread().getName());
    }
    public static void main(String[] args)
    {
        MyRunnable t1 = new MyRunnable();
        MyRunnable t2 = new MyRunnable();
        Thread thread1 = new Thread(t1, "MyThread1");
        Thread thread2 = new Thread(t2);
        thread2.setName("MyThread2");
        thread1.start();
        thread2.start();
    }
}