← Chapter 10 — Threads, Networking & JDBC

34. Multithreading

mixed

Description

A thread is an independent path of execution within a program. Multiple threads can keep a user interface responsive or perform independent tasks at the same time.

Concurrency adds complexity because threads may access shared state in an unpredictable order. Start by using high-level tools such as Runnable and ExecutorService.

Subtopics

Runnable tasks

Description

Runnable represents work with no return value.

Explanation

Pass it to a Thread for a simple demonstration.

Example

Thread worker = new Thread(() -> System.out.println("Working"));

Shared state

Description

Several threads can reach the same object.

Explanation

Synchronization or thread-safe structures protect coordinated updates.

Example

synchronized (lock) { score++; }

Explanation

Calling run executes code on the current thread; calling start creates a new thread that later calls run. Avoid using Thread.sleep as a coordination strategy in production code.

Example

public class ThreadDemo {
    public static void main(String[] args) throws InterruptedException {
        Thread worker = new Thread(() -> System.out.println("Rohan is processing scores"));
        worker.start();
        worker.join();
        System.out.println("Done");
    }
}

Key points

  • A thread is a path of execution.
  • start begins a new thread.
  • Shared state needs coordination.

Video

Open video

Open reference