【问题标题】:Java - access content of Thread variableJava - 访问线程变量的内容
【发布时间】:2015-04-13 11:53:32
【问题描述】:

按照这里的答案:How to know if other threads have finished?

我设法为这样的线程构建了一个侦听器:

    NotifyingThread prcoessCatRegThread =  new processCatFromPage(baseURL, 0, null);
        prcoessCatRegThread.addListener(this);
        prcoessCatRegThread.start();

    @Override
    public void notifyOfThreadComplete(NotifyingThread notifyingThread) {
        // TODO Auto-generated method stub
        System.out.println("Thread calledback returned.");
        System.out.println(notifyingThread);
    }

还有“processCatFromPage”类:

class processCatFromPage extends NotifyingThread{
    int fromPage = 0;
    Integer toPage = 0;
    int cat = 0;
    String baseURL = null;
    static List<Posts> Posts = new ArrayList<Posts>();

    private void processPage(int pageNum){

    }

    processCatFromPage(String baseURL, int fromPage, Integer toPage){

    }


    @Override
    public void doRun() {
        processPage(fromPage);
    }
}

现在我尝试从“notifyOfThreadComplete”中的“processCatFromPage”类访问“Posts”,在eclipse中调试时我可以看到变量,但我不知道如何访问它..

notifyingThread.Posts

出现错误..所以我尝试了任何其他方法..

有什么帮助吗?

非常感谢!:)

我尝试通过代码访问的变量: http://i.stack.imgur.com/dWwgY.png

【问题讨论】:

  • 你为什么不使用ExecutorService
  • 这能回答您的问题吗? help.eclipse.org/luna/…。如果没有,那么请解释你在哪里输入“notifyingThread.Posts”......让它给你错误。
  • @StephenC 我在变量视图窗口中看到变量,就像您附加的链接中一样,但无法在代码中访问它,“notifyingThread.Posts”是我尝试键入时的示例:public void notifyOfThreadComplete(NotifyingThread notifyingThread) { // TODO 自动生成的方法 stub System.out.println("线程回调返回。"); System.out.println(notifyingThread.Posts); }
  • @fge 监听器更适合我需要的目的,谢谢!
  • 错误信息到底是什么?

标签: java multithreading listener


【解决方案1】:

调试器在查找成员时查看对象的运行时类型,即processCatFromPage,编译器查看您声明为NotifyingThread的编译时类型notifyingThread

简单的解决方法是PostsprocessCatFromPage 类的静态成员,因此可以使用processCatFromPage.Posts 访问,如果在范围之外访问,则将其公开。您也可以强制转换 notifyingThread 以便编译器知道它是 processCatFromPage 并以这种方式访问​​该成员,但这是 Java 语言中的一个错误。

全局公共静态成员和向下转换在结构良好的面向对象代码中都没有任何位置,使用static state in concurrent applications 尤其糟糕

【讨论】:

  • 非常感谢!!小问题:当不将 Posts 声明为静态时,我可以从强制转换的“notifyingThread”对象访问它,我想了解更多关于该“错误”的信息以及它为什么会发生,是否不推荐使用?跨度>
  • “错误”是您不需要实例来访问该字段,并且存在不使用实例来访问该字段的语法,因此有两种语法做同样的事情,其中​​一个看起来像是对实例成员的访问,但不是 - stackoverflow.com/questions/3293353/… 。由于直到编写代码以使用它之后才注意到这一点,因此他们无法将其从语言中删除 - stackoverflow.com/questions/610458
猜你喜欢
  • 1970-01-01
  • 2013-08-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-11
  • 2018-07-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多