← Back to Chapters

Creating Threads in Advance Java

? Creating Threads in Advance Java

? Quick Overview

Multithreading in Java allows multiple parts of a program to run concurrently. A thread is a lightweight sub-process that improves application performance and responsiveness.

? Key Concepts

  • Thread
  • Multithreading
  • Concurrency
  • Thread lifecycle
  • Runnable interface

? Syntax / Theory

Java provides two primary ways to create threads:

  • By extending the Thread class
  • By implementing the Runnable interface

? Code Example — Using Thread Class

? View Code Example
// Creating a thread by extending Thread class
class MyThread extends Thread {
public void run() {
System.out.println("Thread is running");
}
public static void main(String[] args) {
MyThread t1 = new MyThread();
t1.start();
}

? Code Example — Using Runnable Interface

? View Code Example
// Creating a thread using Runnable interface
class MyRunnable implements Runnable {
public void run() {
System.out.println("Runnable thread is running");
}
public static void main(String[] args) {
MyRunnable r1 = new MyRunnable();
Thread t1 = new Thread(r1);
t1.start();
}

? Live Output / Explanation

Both examples create a new thread and execute the run() method concurrently with the main thread. The start() method internally calls run().

? Interactive Simulation: The Thread Race

In Java, when you start two threads, you cannot guarantee which one finishes first. The Thread Scheduler decides execution time. Click "Start" below to simulate two threads racing concurrently.

Thread A (Priority 5)
0%
Thread B (Priority 5)
0%
> Ready to start...

✅ Tips & Best Practices

  • Prefer Runnable over extending Thread
  • Never call run() directly
  • Use thread pools for large applications

? Try It Yourself

  • Create two threads printing numbers and characters
  • Use Thread.sleep() to observe execution order
  • Modify thread names using setName()