From the course: Parallel and Concurrent Programming with Java 1

Unlock the full course today

Join today to access over 22,400 courses taught by industry experts or purchase this course individually.

Runnable vs. thread: Java demo

Runnable vs. thread: Java demo - Java Tutorial

From the course: Parallel and Concurrent Programming with Java 1

Start my 1-month free trial

Runnable vs. thread: Java demo

- [Instructor] There are multiple ways to create and run a Thread in Java. One way is to extend the Thread class, which is what I've been doing so far in this course. When you subclass Thread, you can override its run method to provide your own custom code for the Thread to execute. Then, you can create instances of your subclass, and run them as Threads. The other approach is to use the Thread constructor method and pass a Runnable object as its target. Runnable is the interface that a class will need to implement if it will be executed by a Thread. In fact, the Thread class itself implements the Runnable interface. Defining a class that implements the Runnable interface simply requires you to have a run method, similar to the run method that we override when extending the Thread class. To demonstrate how similar it is to use the Thread class versus the Runnable interface, I'll modify this program, which is based on the previous example to demonstrate the life cycle of a Thread, in…

Contents