定义并启动一个线程

创建线程实例的应用程序必须提供在该线程中运行的代码。有两种方法可以做到:

1,提供一个Runnable对象。runnable接口只定义了一个run方法用来包含在线程中执行的方法。Runnable对象被传递给Thread的构造函数,如下HelloRunnable示例:

public class HelloRunnable implements Runnable {

    public void run() {
        System.out.println("Hello from a thread!");
    }

    public static void main(String args[]) {
        (new Thread(new HelloRunnable())).start();
    }

}

2,继承ThreadThread类本身实现了Runnable,尽管它的run方法什么也不做。应用程序可以继承线程,提供自己的运行实现,如下HelloThread示例中:

public class HelloThread extends Thread {

    public void run() {
        System.out.println("Hello from a thread!");
    }

    public static void main(String args[]) {
        (new HelloThread()).start();
    }

}

我们注意到两个例子中都调用了Thread.start以启动线程(Thread)

那么我们应该选择哪一个方式呢?第一个使用Runnable对象的方式更通用,因为Runnable对象不仅可以子类化为Thread,也可以子类化为其他类。 第二种方式在简单的应用程序中更容易使用,但由于任务类必须是线程的子类,因此受到限制。This lesson focuses on the first approach, which separates the Runnable task from the Thread object that executes the task. 本课重点介绍第一种方法,它将runnable任务与执行任务的thread对象分离开来。这种方法不仅更加灵活,而且适用于稍后讨论的高级线程管理api。

猜你喜欢

转载自blog.csdn.net/qq_20320127/article/details/80104385