如何在Runnable中捕获封闭范围

如何在Runnable中捕获封闭范围

本文介绍了如何在Runnable中捕获封闭范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用下面的类在HandlerThread上进行更新,但是我有几个关于变量捕获在Java中如何工作的问题.

I'm trying to do a stream of updates on a HandlerThread using the class below, but I have a couple of questions about how variable capture works in Java.

[1] 是通过引用从随附的示波器中捕获的ret吗?

[1] Is ret captured from the enclosing scope by reference?

[2] this是引用Runnable还是从随附的示波器中捕获?

[2] Does this refer to the Runnable, or is it captured from the enclosing scope?

[奖励] StartStream应该将Runnable发布到处理程序线程,并且仅在Runnable完成时返回.下面的代码能按预期工作吗?

[bonus] StartStream should post a Runnable to the handler thread, and only return when the Runnable has completed. Will the code below work as expected?

public class Stream extends HandlerThread {
    Handler handler = null;

    Stream() {
        super("Stream");
        handler = new Handler(getLooper());
        start();
    }

    private int _startStream() { // Start some repeating update
        return 1;
    }

    public int StartStream() {
        int ret = -1;

        handler.post(new Runnable(){
            @Override public void run() {
                synchronized(this) {
                    ret = _startStream();    // [1]
                    this.notify();           // [2]
                }
            }
        });

        synchronized(this) {
            while(ret == -1) {
                try {
                    this.wait();
                }
                catch (InterruptedException e){}
            }
        }

        return ret;
    }
}

推荐答案

内部类对外部类具有隐式引用.

Inner classes have implicit references to outer class.

要在匿名内部类中使用ret,它应该是最终的.局部变量不能引用为非最终变量的原因是因为该方法返回后,本地类实例可以保留在内存中.它还取决于 java版本.仍然应该是有效最终"或将其移至成员变量.

To use ret in anonymous inner class it should be final. The reason local variables cannot reference as non-final is because the local class instance can remain in memory after the method returns. It also depends on java version. Still it should be "effectively final" or move it to a member variable.

this指的是Runnable,您应该使用Stream.this将其括起来.

this refers to the Runnable, you should use Stream.this for enclosing one.

这篇关于如何在Runnable中捕获封闭范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 22:26