Documentation

The Java™ Tutorials
Hide TOC
Defining and Starting a Thread定义和启动线程
Trail: Essential Java Classes
Lesson: Concurrency
Section: Thread Objects

Defining and Starting a Thread定义和启动线程

An application that creates an instance of Thread must provide the code that will run in that thread. 创建Thread实例的应用程序必须提供将在该线程中运行的代码。There are two ways to do this:有两种方法可以做到这一点:

Notice that both examples invoke Thread.start in order to start the new thread.请注意,这两个示例都调用Thread.start以启动新线程。

Which of these idioms should you use? 这些习语你应该用哪一个?The first idiom, which employs a Runnable object, is more general, because the Runnable object can subclass a class other than Thread. 第一个习惯用法是使用Runnable对象,它更为一般,因Runnable对象可以为Thread以外的类创建子类。The second idiom is easier to use in simple applications, but is limited by the fact that your task class must be a descendant of Thread. 第二种习惯用法更易于在简单应用程序中使用,但受任务类必须是Thread的后代这一事实的限制。This lesson focuses on the first approach, which separates the Runnable task from the Thread object that executes the task. 本课程重点介绍第一种方法,它将Runnable任务与执行任务的Thread对象分离。Not only is this approach more flexible, but it is applicable to the high-level thread management APIs covered later.这种方法不仅更加灵活,而且适用于后面介绍的高级线程管理API。

The Thread class defines a number of methods useful for thread management. Thread类定义了许多对线程管理有用的方法。These include static methods, which provide information about, or affect the status of, the thread invoking the method. 其中包括static方法,这些方法提供有关调用该方法的线程的信息或影响该线程的状态。The other methods are invoked from other threads involved in managing the thread and Thread object. 其他方法从管理线程和Thread对象所涉及的其他线程调用。Well examine some of these methods in the following sections.我们将在下面的部分中研究其中的一些方法。


Previous page: Thread Objects
Next page: Pausing Execution with Sleep