This is a Java syntax question, but just for some background.
Using android, I created a small app that went really slow and often crashed because when a button was clicked the onClick() method changed button images for various buttons. It was really clunky and slow and I found out after a search on the net that the problem is pretty common, and when changing lots of images in the onClick() method, its best to put them in a separate thread. And some kind person gave the code for doing this.
new Thread(new Runnable() {
public void run() {
quest.post(new Runnable() {
public void run() {
correct = nextQ();
}
});
}
}).start();
The nextQ() method and the “quest” TextView are mine. It’s not really relevant to my question what they do, but nextQ does a database search and updates images, and running it outside the thread is really slow and crashy.
Now I copied and pasted this code into my code and it runs fine. A happy ending. But I dont feel comfortable using code I don’t understand. And I don’t know Java very well. SO I researched as best I could anonymous inner classes, but I’m still stumped by the code.
So the anonymous class extends thread, and as it’s argument uses an anonymous class, implementing runnable, in which the “meat” of the code is placed..
Questions:
1)Why would I do this? I can understand using thread OR runnable, but why together?
2)How does this work? I went back to basics of thread and runnable, but I don’t see how you use them together this way.
RunnableinterfaceThreadclass. So you are not extending Thread, you are just instantiating it, and pass an argument.start()the thread. Thus therun()method of the passed argument will be invoked in a new thread.You need to do this, because:
Runnabledefines what gets executedThreadactually executes it.Your confusion is understandable, since a
Threadis alsoRunnable. That’s why in Java 5 the executors framework was introduces, which separated the execution mechanism (an executor) from the executed code (RunnableorCallable).