⬅ Previous Next ➡

Multithreading

Multithreading in Java: Thread & Runnable, Lifecycle, Synchronization, Inter-thread Communication, Priorities & Daemon
  • Multithreading means running multiple threads (smallest unit of execution) at the same time.
  • Benefits: better CPU utilization, faster tasks (like downloading + UI), responsive applications.
  • Java supports multithreading using Thread class and Runnable interface.

1) Thread Creation using Thread Class

  • Create a class that extends Thread and override run().
  • Start thread using start() (not run()).
class MyThread extends Thread {
    public void run() {
        for (int i = 1; i  {
            for (int i = 1; i  {
            for (int i = 1; i  {
            try {
                for (int i = 1; i  {
            try {
                for (int i = 1; i  System.out.println("Low priority"));
        Thread t2 = new Thread(() -> System.out.println("High priority"));

        t1.setPriority(Thread.MIN_PRIORITY); // 1
        t2.setPriority(Thread.MAX_PRIORITY); // 10

        t1.start();
        t2.start();
    }
}

7) Daemon Threads

  • Daemon thread runs in background (like GC).
  • When all non-daemon threads finish, JVM ends daemon threads automatically.
  • Set using setDaemon(true) before start().
class DaemonDemo {
    public static void main(String[] args) {
        Thread bg = new Thread(() -> {
            while (true) {
                System.out.println("Background task...");
                try { Thread.sleep(200); } catch (Exception e) { }
            }
        });

        bg.setDaemon(true); // must be before start
        bg.start();

        System.out.println("Main work done!");
    }
}

8) Quick Notes

  • Always use start() to run thread in parallel.
  • Use synchronized to avoid race condition.
  • wait/notify used for cooperation between threads.
  • Priority is a hint, not a guarantee.
  • Daemon threads stop automatically when main threads end.
⬅ Previous Next ➡