How does java.lang.Runnable relate to the Command pattern?
Runnable is structurally a Command: it's a functional interface with a single method, run(), that takes no parameters and returns nothing — the exact same shape as a Command interface's execute() method. When code hands a Runnable to a Thread constructor or submits it to an ExecutorService, it's doing precisely what an Invoker does with a Command: holding a self-contained, executable unit of work without needing to know what that work actually involves. The executor framework itself acts as the Invoker, queueing and eventually calling run() on each submitted Runnable, completely decoupled from the specific logic each one contains — which is exactly why task queues and thread pools are one of the most common real-world applications of this pattern.
Ready to master this question?
Generate a complete walkthrough — background, the full answer in plain language, a working code example explained line by line, a real-world scenario, common mistakes, and how this same question gets asked in different ways.
Sign in to generate a response