简体   繁体   English

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

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

I found the following excerpt in a Java Textbook: 我在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"

Shouldn't the last line be 不应该是最后一行

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

Am I correct? 我对么?

Could somebody provide sample code that illustrates the above excerpt? 有人可以提供示例代码来说明上述摘录吗?

You are correct. 你是对的。

If you create an instance of Thread without overriding run() of supplying a Runnable , the thread would execute the default empty run() method. 如果在不重写提供Runnable run()的情况下创建Thread实例,则该线程将执行默认的空run()方法。

I wonder if this quote is accurate, as it specifically mentions sub-classing Thread, but the code Thread t = new Thread(); 我想知道这个引用是否准确,因为它特别提到了子类的Thread,但是代码Thread t = new Thread(); clearly doesn't. 显然没有。

Basically you are talking about runtime polymorphism. 基本上你在谈论运行时多态性。 Yes you could do that. 是的,你可以做到这一点。 See following exmaple: 见下面的例子:

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

You can override the run method "inline" with an anonymous subclass: 您可以使用匿名子类覆盖run方法“inline”:

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

Not that there are a lot of advantages to this over supplying a separate Runnable class. 并不是说提供单独的Runnable类有很多优点。 You rearely need a thread, that just does one thing and dies, it's kinda wasteful. 你真的需要一个线程,只做一件事而死,这有点浪费。 A better way is to use a ThreadPool , which has a bunch of threads, that are available for executing any task when you need them. 更好的方法是使用ThreadPool ,它有一堆线程,可以在需要时执行任何任务。 That way, you reduce the overhead of starting up and destroying the thread every time. 这样,您每次都可以减少启动和销毁线程的开销。

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

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