Threads in Java

LEELA S
2 min readMar 22, 2022

--

A thread, in the context of Java, is the path followed when executing a program. All Java programs have at least one thread, known as the main thread, which is created by the Java Virtual Machine (JVM) at the program’s start, when the main() method is invoked with the main thread.

Creating a thread

There are two ways to create a thread.

It can be created by extending the Thread class and overriding its run( ) method:

Extend Syntax

Another way to create a thread is to implement the Runnable interface:

Running Threads

If the class extends the Thread class, the thread can be run by creating an instance of the class and call its start( ) method:

Output:

This code is outside of the thread
This code is running in a thread

If the class implements the Runnable interface, the thread can be run by passing an instance of the class to a Thread object's constructor and then calling the thread's start( ) method:

Implement Example

Output

This code is outside of the thread
This code is running in a thread

--

--

LEELA S
LEELA S

No responses yet