background image

9
  2.继承 Thread 并实现其 run 方法:
1 public class HelloThread extends Thread {
2     public void run() {
3         System.out.println("Hello World!");
4     }
5     public static void main(String args[]) {
6         (new HelloThread()).start();
7     }
8 }
9
  如何选择使用哪种方式呢?第一种模式更为通用,实现一个 Runnable 接口允许你继
承并复用某类。第二种更简单,缺点是必须继承 Thread。你可以根据具体情况选择。
  Thread 对象中定义了一些有用的方法来管理线程的生命周期:
  1.public static void sleep(long millis)throws InterruptedException 方法,该
方法挂起当前线程一段时间,主动让出处理器让其他线程使用。sleep 方法还可以用来控
制执行的速度。注意这个方法在挂起线程时,有可能被其他线程中断挂起,因此不能依赖
其时间参数来定时。
  2.public void interrupt()方法,该方法中断某线程正在做的事情,告诉它某些事情
发生了需要处理。程序员需要捕捉这个中断异常,并在异常处理中执行应该做的动作。接
受 中 断 的 方 式 有 两 种 , 一 种 是 被 中 断 线 程 目 前 正 在 执 行 一 个 能 抛 出
InterruptedException 的方法,比如 sleep 或者 Object.wait 等方法,还比如一些可以
被 interrupted 的 SeverSocket.accept 方法等等。下面是示例代码:
1 for (int i = 0; i < importantInfo.length; i++) {
2     //Pause for 4 seconds
3     try {
4         Thread.sleep(4000);
5     } catch (InterruptedException e) {
6         //We've been interrupted: no more messages.
7         return;
8     }
9     //Print a message
10     System.out.println(importantInfo[i]);
11 }
12
  另一种是程序正在执行一些不抛出 InterruptedException 的动作,这时该线程要
负责定期使用 interrupted()方法检查当前线程是否受到中断信号,然后做相应处理。下
面是示例代码:
1 for (int i = 0; i < inputs.length; i++) {
2     heavyCrunch(inputs[i]);
3     if (Thread.interrupted()()) {
4         //We've been interrupted: no more crunching.