Creating Threads: Multitasking

Creating Threads: Multitasking in Java: Imagine you are a Chef in a kitchen. Single-threaded: You chop the onions, then you boil the water, then you grill the…

Concept Explanation

Imagine you are a Chef in a kitchen.

  • Single-threaded: You chop the onions, then you boil the water, then you grill the steak. One task after another.
  • Multi-threaded: You hire two assistants. Assistant A chops onions, Assistant B boils water, and you grill the steak. All three things happen at the same time.

In Java, a Thread is one of those assistants. They allow your program to perform background tasks (like downloading a file) while the user keeps clicking buttons.


Syntax or Core Structure

Method 1: Extending the Thread class

class MyAssistant extends Thread {
    public void run() {
        System.out.println("Assistant is working...");
    }
}

// In main:
MyAssistant a = new MyAssistant();
a.start(); // DO NOT call run() directly!

Common Mistakes

  • Calling a.run(): If you call run(), it runs on the Main Thread like a normal method. You MUST call start() to create a new thread.
  • Over-threading: Creating 1,000 threads will make your computer slower, not faster (the "Too many cooks" problem).

Practice Exercises

  1. The Double Print: Create two threads. Thread A prints "Apple" 10 times, and Thread B prints "Banana" 10 times. Observe how they mix in the console.
  2. The Identity Check: Inside a thread, use Thread.currentThread().getName() to print the name of the thread.
  3. The Start vs Run: Try calling run() instead of start() and see if the thread name changes.