AllRounder.ai
Chapters in this course

Enrol to start learning

Reading is open to everyone. Enrolling is free, and it is what unlocks the audio lessons, practice tests and progress tracking.

Enrol free

14.3. Creating Threads in Java

Interactive Audio Lesson

Session 1: Creating Threads Using the Thread Class

Unlock the classroom podcast

The transcript is free to read. A free account plays the conversation back.

Sarah
SarahInstructor

Today we're going to learn how to create threads in Java using the Thread class. When you extend the Thread class, you only need to override the run() method to define what the thread will do. Can anyone explain what the run() method is?

Noah
Noah

The run() method contains the code that will execute when the thread starts.

Sarah
SarahInstructor

Exactly! Let’s see a basic example. In this code, we create a class called MyThread that extends Thread, and inside it, we override the run() method to print a message. What happens when we call t1.start()?

Isabella
Isabella

It starts a new thread and calls the run() method in that thread.

Sarah
SarahInstructor

Good job! And remember, we never call the run() method directly; we always use start(). Now, can anyone remember how to instantiate and start the thread using this class?

Akash
Akash

We create an object of MyThread and then call start() on that object.

Sarah
SarahInstructor

Perfect! To summarize, we use the Thread class by overriding run(), creating an instance, and starting it with start().

Session 2: Creating Threads Using the Runnable Interface

Unlock the classroom podcast

The transcript is free to read. A free account plays the conversation back.

Robert
RobertInstructor

Next, let’s explore how to create threads using the Runnable interface. This method lets us implement the run() method in a separate class. Why might we want to use this approach?

Ananya
Ananya

It allows us to separate the thread's behavior from the execution. Plus, we can implement other interfaces too.

Robert
RobertInstructor

Exactly! Good thinking! For instance, we can create a class MyRunnable that implements Runnable. When we create a thread, we pass an instance of MyRunnable as an argument. What command do we use to start this thread?

Noah
Noah

We still call start() on the Thread object, right?

Robert
RobertInstructor

"That's correct! Let’s see the example: