23.4. Creating and Executing Threads

The preferred means of creating multithreaded Java applications is by implementing the Runnable interface (of package java.lang). A Runnable object represents a “task” that can execute concurrently with other tasks. The Runnable interface declares a single method, run, which contains the code that defines the task that a Runnable object should perform. When a thread executing a Runnable is created and started, the thread calls the Runnable object’s run method, which executes in the new thread.

23.4.1. Runnables and the Thread Class

Class PrintTask (Fig. 23.4) implements Runnable (line 5), so that multiple PrintTasks can execute concurrently. Variable sleepTime (line 7) stores a random integer value from ...

Get Java™ How to Program, Seventh Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.