Skip to content
C

Thread

A thread is a single, independent path of execution within a program. A Java program always starts with at least one thread (the main thread), but it can create additional threads to perform tasks alongside it.


1. What is a Thread?

A thread is a single, independent path of execution within a program. A Java program always starts with at least one thread (the main thread), but it can create additional threads to perform tasks alongside it.

2. Why is it used?

Threads let a program perform multiple tasks at (roughly) the same time — like downloading a file while still allowing a user to interact with the app — instead of doing everything one task at a time, in strict sequence.

3. Real-Life Example

Think of a restaurant kitchen where one chef prepares a starter while another chef prepares the main course, both working at the same time instead of one waiting for the other to finish completely. Each chef here is like a separate thread.

4. Syntax

java
class MyThread extends Thread { public void run() { // code to run in this thread } }

5. Example Program

java
class MyThread extends Thread { public void run() { System.out.println("Thread is running"); } } public class ThreadDemo { public static void main(String[] args) { MyThread t = new MyThread(); t.start(); } }

Output:

Thread is running

6. Key Points to Remember

  • A thread's task is written inside its run() method.
  • Call start() to actually begin a new thread — calling run() directly just runs it like a normal method, on the current thread, not as a separate thread.
  • Every Java program has at least one thread automatically, called the main thread.