繁体   English   中英

如何在不使用Runnable实现的情况下运行线程?

[英]How to run threads without using Runnable implementations?

我在Java教科书中找到了以下摘录:

"I've seen examples that don't use a separate 
Runnable Implementation, but Instead Just make a 
subclass of Thread and override the Thread's runO 
method. That way,you call the Thread's no-arg 
constructor when you make the new thread; 
Thread t = new Thread(); //no Runnable"

不应该是最后一行

Thread t = new <Some class that extends Thread class and over rides its run method>();

我对么?

有人可以提供示例代码来说明上述摘录吗?

你是对的。

如果在不重写提供Runnable run()的情况下创建Thread实例,则该线程将执行默认的空run()方法。

我想知道这个引用是否准确,因为它特别提到了子类的Thread,但是代码Thread t = new Thread(); 显然没有。

基本上你在谈论运行时多态性。 是的,你可以做到这一点。 见下面的例子:

class Flight extends Thread {
    public void run() {
        System.out.println("Hello World.. I took off");
    }
}

public static void main(String[] args) {
    Flight flight = new Flight();
    Thread myflight = new Flight();//See how i used runtime polymorphism.
    flight.start();
    myflight.start();
}

您可以使用匿名子类覆盖run方法“inline”:

new Thread() {
    public void run() {
        doStuffInPaarralel();
    }
}.start();

并不是说提供单独的Runnable类有很多优点。 你真的需要一个线程,只做一件事而死,这有点浪费。 更好的方法是使用ThreadPool ,它有一堆线程,可以在需要时执行任何任务。 这样,您每次都可以减少启动和销毁线程的开销。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM