多线程Thread Runable

发表于:2008-06-11来源:作者:点击数: 标签:线程ThreadRunable
关键字:多线程Thread Runable 1. 多线程 1.1 创建线程类 在 Java 中可以简单的从Thread类中继承创建自己的线程类: public class MyFirstThread extends Thread { public void run() { . . .} } 说明: (1) Thread类位是 java .lang包中,所以可以不用显示
关键字:多线程Thread Runable

 1. 多线程
  1.1 创建线程类
  在Java中可以简单的从Thread类中继承创建自己的线程类:

public class MyFirstThread extends Thread {

    public void run() { . . .}

}

  说明:

 (1) Thread类位是java.lang包中,所以可以不用显示import;

 (2) 从Thread类中继承下来的类最好重载run()方法,以运行需要的代码;

  可以按以下方法实例化并运行线程:

  MyFirstThread aMFT = new MyFirstThread();

  aMFT.start();

  说明:

  (3) 实例化线程类后,系统会初始化一些参数,主要是为线程创建名称,把新的线程加入指定的线程组,初始化线程运行需要的内存空间,指定新线程的优先级别,指定它的守候线程;

  (4) start方法是Thread类中的方法,它会调用run方法,在新的线程中运行指定的代码;

  (5) 除了start方法外,从Thread继承下来的类还具有其它一些主要的方法:stop,suspend,resume等;

  以下是一个完整的Thread派生类:

  1: public class ComplexThread extends Thread {

   2:     private int delay;

   3:

   4:     ComplexThread(String name, float seconds) {

   5:         super(name);

   6:         delay = (int) seconds * 1000;   // delays are in milliseconds

   7:         start();                        // start up ourself!

   8:     }

   9:

  10:     public void run() {

  11:         while (true) {

  12:             System.out.println(Thread.currentThread().getName());

  13:             try {

  14:                 Thread.sleep(delay);

  15:             } catch (InterruptedException e) {

  16:                 return;

  17:             }

  18:         }

  19:     }

  20:

  21:     public static void main(String argv[]) {

原文转自:http://www.ltesting.net