简体   繁体   中英

Java, what do you call this? and why )};

I am going through Hello Android (Android PDF/tutorial) and have now seen this syntax a couple of times. Can someone please explain to me what Java syntax is used when run Runnable is defined?

private class AndroidBridge {

    public void callAndroid(final String arg) { // must be final
        handler.post(new Runnable() {
            public void run() {
                Log.d(TAG, "callAndroid(" + arg + ")" );
                textView.setText(arg);
            }
            ...

Is the code defining a Runnable object and overriding it's run method?

The .post method expects a Runnable object, which in your code sample is declared anonymously and passed as the argument.

That will start a new thread for some long-running process.

The thread constructor needs a Runnable object, which has a run method that's called when the thread is ready.

When many Java apps start, all of the operations pile up on one thread, including the UI. I mainly use threads to avoid freezing up the UI if I'm doing something "heavy".

You've seen this happen when you click "execute" or something, and the UI suddenly is less than responsive. This is because the current thread doesn't have enough resources to build the UI and do whatever "execute" is asking.

So, sometimes that's done elsewhere, on a different thread, which needs a Runnable object.

It's worth noting that multithreading (where you make more than one thread on purpose) is notoriously difficult to work with, for debugging reasons mostly, IMO. But it is a useful tool, of course.

As Dave Newton indicated, this is an anonymous inner class implementing the Runnable interface.

As to why one would want to use this, it could be thought of as syntactic sugar of sorts. You'll notice that in your example, the code in run() has access to the same scope as where the anonymous inner class itself is defined.

This simplifies access to those members, as if you defined the class externally, you'd have to pass in a reference to any object whose members you wanted to invoke/use.

In fact, IIRC, this is actually what happens when Java compiles the anonymous inner class; if there are references to the outer containing class, the compiler will create a constructor that passes in a reference to the outer containing class.

该代码定义了一个匿名内部类,该类实现了Runnable接口,并实现了run方法以执行适当的操作。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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