建立并使用线程

建立并使用线程

两种方式,建立新的线程:html

实现 Runnable 接口,Runnable 接口定义了一个方法:run。run 方法中的代码,将在建立的线程中执行。实现了 Runnable 接口的对象,做为 Thread 构造方法的参数。java

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();
    }

}

继承 Thread。Thread 类实现了 Runnable 接口,尽管它的 run 方法内什么也没有。一个类能够继承自 Thread,并重写 run 方法。oracle

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 去建立一个新的线程线程

这两种方式,该选哪种?

实现 Runnable 接口,是经常使用的建立新线程的方式。code

  1. 实现 Runnable 接口的类,能够继承自其它的类,而不单单是 Thread。更加灵活。htm

  2. 适用于一些高阶线程管理的 APIs对象

继承 Thread,用起来彷佛更加简单一点。缺点是,没法继承其它类 (java)继承

建议使用第一种。接口

参考资料

相关文章
相关标签/搜索