Nearby lessons

69 of 125

Java - Creating a Thread (Thread vs Runnable)

📌 What You Will Learn
  • What a thread is and how it is different from a process
  • Two ways to create a thread: Thread class and Runnable interface
  • The thread life cycle (states)
  • How threads cooperate: synchronized, wait and notify
  • The modern way: Executors, Callable and lambdas

Creating a Thread (Thread vs Runnable) is a core concept of the Java language. This lesson explains Two Ways to Create a Thread with complete, runnable code examples, clear step-by-step explanations, and common mistakes to avoid with exam-style MCQs at the end.

Two Ways to Create a Thread

Method 1 — Extend the Thread class

Output may differ every run — that is the magic of threads. Both loops run at the same time, so the printed order is not fixed.

Method 2 — Implement the Runnable interface (Recommended)

Java does not allow a class to extend more than one class. If your class already extends some class, it cannot also extend Thread. The solution: implement Runnable and give the job to a Thread object.

Example01
JCode Cell
1class MyThread extends Thread {
2 public void run() { // override run() - the thread's job
3 for (int i = 1; i <= 5; i++) {
4 System.out.println("Child: " + i);
5 }
6 }
7}
8 
9class Test {
10 public static void main(String[] args) {
11 MyThread t = new MyThread();
12 t.start(); // start() creates the thread and calls run()
13 for (int i = 1; i <= 5; i++) {
14 System.out.println("Main: " + i);
15 }
16 }
17}
Output
Main: 1 Child: 1 Child: 2 Main: 2 Main: 3 Child: 3 ... (order varies)
📝 Key Takeaways
  • A thread is a small unit of work; a process is a running program.
  • Create a thread by extending Thread or (better) implementing Runnable.
  • Life cycle: NEW -> RUNNABLE -> BLOCKED/WAITING/TIMED_WAITING -> TERMINATED.
  • Shared data races when many threads change it; synchronized gives a lock.
  • wait/notify let threads talk; they need the lock.
  • Deadlock = threads waiting on each other's locks; avoid by consistent lock order.
  • Real projects use Executors + Callable instead of raw threads.

🧠 Test Your Knowledge

1 Questions
Progress: 0 / 1