Loading...

Go Back

Next page
Go Back Course Outline

Java Full Course


Multithreading and Concurrency in Java

๐Ÿงต What is Multithreading?

Multithreading means doing many tasks at the same time in a single program.

Each task runs in a thread (like a small worker in a factory).

For example:

  • โžก๏ธ One thread can play music
  • โžก๏ธ Another thread can download a file
  • โœ… Both happen at the same time!

๐Ÿ”น 1. Thread Class and Runnable Interface

Java gives two main ways to create a thread:

โœ… Way 1: Extend the Thread class

class MyThread extends Thread {
    public void run() {
        System.out.println("This is my thread running");
    }
}
MyThread t = new MyThread();
t.start(); // Start the thread

โœ… Way 2: Implement the Runnable interface

class MyRunnable implements Runnable {
    public void run() {
        System.out.println("Runnable thread is running");
    }
}
Thread t = new Thread(new MyRunnable());
t.start();

โœ… Tip: Use Runnable if you want to extend another class too (Java allows only one superclass).

๐Ÿ”น 2. Thread Lifecycle (Threadโ€™s Life Stages)

Just like humans are born, grow, and die โ€” threads also have stages:

New โ†’ Ready โ†’ Running โ†’ Waiting โ†’ Dead
StageWhat happens?
NewThread is created
ReadyReady to run but waiting for CPU
RunningIt is running now
WaitingWaiting for something to finish
DeadFinished its task

๐Ÿ”น 3. Thread Priorities

Every thread has a priority from 1 to 10.

Higher number = more important (but not always guaranteed to run first).

Thread t = new Thread();
t.setPriority(10); // Highest

Note: Java tries to give more time to important threads, but it's up to the OS.

๐Ÿ”น 4. Synchronization (Avoiding Confusion)

Imagine 2 people writing on the same paper at the same time โ€“ messy, right?

If two threads change the same data, they can cause problems.

We use synchronization to let only one thread use it at a time.

synchronized void deposit() {
    // only one thread can enter here at a time
}

๐Ÿ”น 5. Inter-thread Communication

Sometimes, one thread must wait for another to finish something.

Example:

  • Thread A: "Iโ€™m waiting..."
  • Thread B: "Okay, Iโ€™m done! You can go!"

We use:

  • wait() โ€“ pause the thread
  • notify() โ€“ wake up one thread
  • notifyAll() โ€“ wake up all waiting threads

These must be used inside synchronized blocks!

๐Ÿ”น 6. Deadlock (A Lock Fight!)

Deadlock happens when two threads are waiting for each other, and no one continues.

// Thread A locks Pen, then wants Notebook
// Thread B locks Notebook, then wants Pen

๐Ÿ›‘ Avoid deadlocks by:

  • Locking things in the same order
  • Using timeout methods like tryLock()
  • Not using too many nested locks

๐Ÿ”น 7. Executor Framework (Thread Manager)

Instead of making threads manually, Java gives you an Executor (like a smart thread manager).

ExecutorService executor = Executors.newFixedThreadPool(2);

executor.submit(() -> {
    System.out.println("Doing work using Executor");
});

executor.shutdown();

โœ… Benefits:

  • Reuses threads (saves memory)
  • Easy to control
  • Can run many tasks in order

๐ŸŽฏ Summary for Beginners

ConceptSimple Meaning
ThreadA mini-program running inside your main program
RunnableA way to make a class โ€œthreadableโ€
SynchronizationStops two threads from using the same thing at the same time
wait/notifyOne thread can pause and wait for another
DeadlockTwo threads stuck waiting for each other
ExecutorA smart manager that handles threads for you
Go Back

Next page