简体   繁体   English

非静态嵌套线程-来自另一个类的访问(Java)

[英]Non-static nested thread - access from another class (Java)

I'm having some trouble creating a thread object in another class (to which it is defined); 我在另一个类(定义它的类)中创建线程对象时遇到一些麻烦;

It is nested like so: 它像这样嵌套:

public final class Sculpture extends UiApplication
{  
     final class ScreenThread extends Thread
     {
        //thread I want to access
     }
}  

So in my other class I want to create the thread object, so I try; 因此,在另一个类中,我想创建线程对象,因此我尝试;

Sculpture.ScreenThread test = (new Sculpture).new ScreenThread();

- This errors (in BlackBerry Eclipse plugin) saying "No enclosing instance of type Sculpture is accessible." -此错误(在BlackBerry Eclipse插件中)显示“无法访问Sculpture类型的封闭实例”。

As far as I can tell I can't un-nest this because it causes a lot of the code not to work (I assume it relies on UiApplication), I also can't make it static for the same reason. 据我所知,我不能取消嵌套,因为它导致很多代码无法正常工作(我假设它依赖于UiApplication),出于同样的原因,我也不能使其变为静态。

Any ideas what I'm doing wrong? 有什么想法我做错了吗?

Thanks. 谢谢。

In your current code you define an inner class which requires an instance of the outer, containing class in order to be instantiated: 在当前代码中,您定义一个内部类,该内部类需要外部包含类的实例才能实例化:

ScreenThread screenThread = new Sculpture().new ScreenThread();

If you do not need access to the outer classes context then you may want to define a nested class instead: 如果不需要访问外部类上下文,则可能需要定义一个嵌套类:

public final class Sculpture extends UiApplication {  
     static final class ScreenThread extends Thread {
        //thread I want to access
     }
}  

Which you can then import and instantiate 'normally' (ie, without first creating an instance of the outer, containing class): 然后可以“正常”导入和实例化(即,无需先创建包含外部类的实例):

ScreenThread screen = new ScreenThread();

One final note, it's generally bad practice to sub-class Thread . 最后一点,子类化Thread通常是不好的做法。 It's much better practice to implement Runnable instead. 相反,实现Runnable是更好的做法。

You aren't creating your Sculpture . 您不是要创建Sculpture The call should look like new Sculpture().new ScreenThread() . 该调用应类似于new Sculpture().new ScreenThread()

看起来您只是忘记了new Sculpture之后的()?

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

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