简体   繁体   English

Runnable类中的线程成员

[英]Thread member inside Runnable class

Is it a bad practice to put a Thread member inside a Runnable class like this: 像这样将Thread成员放入Runnable类中是不好的做法:

public class A implements Runnable{
    public Thread thread;
    public A(){
        thread = new Thread(this)
    }
    public void run(){
        ...
    }
}

And invoke this Runnable class like that: 并像这样调用此Runnable类:

A a = new A();
a.thread.start();
...
a.thread.join();
...

Yes, because there is no (architectural) guarantee, that a Runnable always has the same thread. 是的,因为没有(架构上的)保证,因此Runnable始终具有相同的线程。 If you put it into an executor, your code will produce several errors. 如果将其放入执行程序中,您的代码将产生一些错误。 While your code works in your special case, you destroy the separation between thread and Runnable, and that one was created for a good reason. 当您的代码在特殊情况下运行时,您将破坏线程与Runnable之间的分隔,并且创建该分隔是有充分理由的。

If you need to access the actual thread for any reason, it is much better to use Thread.currentThread() . 如果出于任何原因需要访问实际线程,最好使用Thread.currentThread()

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

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