Java Threads 101: A Beginner’s Guide to Multitasking Like a Pro

iswarya writes
Javarevisited
Published in
4 min readAug 25, 2024

Welcome to the exciting world of Java threads! Threads might seem like a complex topic, but they’re a fantastic tool to make your programs run smoother and more efficiently. Ready to dive in? Let’s break down threads in the simplest way possible!

What Are Java Threads?

Think of threads as tiny workers inside your program. Each thread handles a specific task simultaneously with other threads, making your program more efficient. For example, in MS Word, one thread could handle formatting your document while another processes your keystrokes. As Tim Berners-Lee, the inventor of the World Wide Web, wisely said, “The Web does not just connect machines, it connects people.” Similarly, threads connect various tasks, enhancing how your program functions.

Photo by Josue Isai Ramos Figueroa on Unsplash

Threads and Shared Memory: The Dynamic Duo

Threads operate within processes and share the same memory space. Imagine a big office where everyone works at the same desk. This setup allows for fast communication and collaboration. Threads are perfect for tasks requiring quick responses and high efficiency, like games or real-time applications.

Multitasking: Doing More with Threads

Multitasking is like juggling multiple tasks at once, and threads help you do it efficiently. Here are two main ways computers multitask:

1. Process-Based Multitasking:

  • Heavyweight Processes: Each task runs in its own separate space, like having separate offices. This can be slow because moving data between offices is tricky and time-consuming.

2. Thread-Based Multitasking:

  • Lightweight Threads: Threads share the same office space, making it easier and faster to pass information around. This setup allows for quick switching and efficient multitasking.

As Steve Jobs once said, “The only way to do great work is to love what you do.” Threads help make your work more manageable, allowing you to focus on creating great software.

Why Threads Are Awesome

Threads are great because:

  • They’re Lightweight: They don’t use up a lot of resources.
  • They Communicate Easily: Threads can share data quickly, making multitasking smoother.
  • They Keep Things Responsive: Even if one thread is stuck or slow, others can keep working.

The Journey of a Thread: From Start to Finish

Threads go through several stages during their “lifetime”:

1. New State: The thread has just been born, and nothing has happened yet.

2. Active State: When you start a thread, it moves to the active state. There are two parts:

  • Runnable State: The thread is ready to work and is waiting for its turn.
  • Running State: When the thread gets CPU time, it’s actively working on its task. After its turn is over, it goes back to waiting.

3. Waiting/Blocked State: Sometimes, a thread has to wait. For example, if it needs a resource that’s currently in use by another thread, it will be in this waiting or blocked state.

4. Timed Waiting State: To avoid waiting forever, threads can sleep for a set amount of time. This helps them avoid being stuck in a queue indefinitely.

5. Terminated State: Once a thread finishes its task or encounters an error, it enters the terminated state and can no longer run.

The Main Thread: The VIP of Your Program

Every Java program starts with a main thread. This thread is like the project manager who makes sure everything gets started. As Java’s creator James Gosling puts it, “The goal is to turn data into information, and information into insight.” The main thread helps achieve this by starting the main() method.

Creating Threads in Java: Two Fun Ways

You can create threads in Java using two main methods:

1. Extending the Thread Class:

public class MyThread extends Thread {
public void run() {
System.out.println("Thread is running...");
}
public static void main(String[] args) {
MyThread t = new MyThread();
t.start(); // Start the thread
}
}

2. Implementing the Runnable Interface:

public class MyRunnable implements Runnable {
public void run() {
System.out.println("Thread is running...");
}
public static void main(String[] args) {
Thread t = new Thread(new MyRunnable());
t.start(); // Start the thread
}
}

Cool Examples of Threads in Action

1. Thread with a Name:

public class NamedThread {
public static void main(String[] args) {
Thread t = new Thread("MyNamedThread");
t.start();
System.out.println("Thread name: " + t.getName());
}
}

2. Runnable with a Name:

public class NamedRunnable implements Runnable {
public void run() {
System.out.println("Thread is running...");
}
public static void main(String[] args) {
Thread t = new Thread(new NamedRunnable(), "MyNamedRunnableThread");
t.start();
System.out.println("Thread name: " + t.getName());
}
}

Exploring the Thread States in Java

Here’s a fun little example to show how threads move between different states:

public class ThreadStateDemo implements Runnable {
public static Thread t1;
public static void main(String[] args) {
ThreadStateDemo demo = new ThreadStateDemo();
t1 = new Thread(demo);
System.out.println("Initial state of t1: " + t1.getState());
t1.start();
System.out.println("State of t1 after start(): " + t1.getState());
}
public void run() {
try {
Thread.sleep(100);
System.out.println("State of t1 after sleep(): " + t1.getState());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

Conclusion

Java threads might seem a bit daunting at first, but they’re incredibly powerful tools that can make your programs faster and more efficient. By understanding how threads work and experimenting with them, you’ll see how they can enhance your coding experience. As Albert Einstein once said, “In the middle of difficulty lies opportunity.” Embrace the opportunity to explore threads and see how they can transform your programming!

If you enjoyed this guide, share it with your fellow developers and spread the knowledge about the power of Java threads. Happy coding!

--

--

iswarya writes
Javarevisited

Iswarya | Growth, Cooking, Tech Enthusiast 🌱🍳📱