Example Of Multithreading In Java Code Examples

3 min read

Multithreading in Java enables a single program to perform multiple operations at the same time, improving responsiveness and resource utilization. This article provides a comprehensive example of multithreading in java code examples, illustrating how to create, manage, and synchronize threads effectively.

Understanding Threads in Java

What is a Thread?

A thread is the smallest unit of execution within a process. In Java, a thread is represented by the java.lang.Thread class or by implementing the Runnable interface. Each thread shares the same memory space as its parent process, which allows for efficient communication but also introduces the need for careful coordination.

Benefits of Multithreading

  • Improved performance on multi‑core processors by executing tasks concurrently.
  • Better user experience in GUI applications, where background tasks do not freeze the interface.
  • Efficient resource usage, as idle threads can be scheduled for other work.

Creating Threads

Extending the Thread Class

One of the simplest ways to create a thread is to subclass Thread and override the run() method Easy to understand, harder to ignore. Practical, not theoretical..

class MyThread extends Thread {
    @Override
    public void run() {
        System.out.println("Thread " + getName() + " is running");
        for (int i = 0; i < 5; i++) {
            System.out.println(getName() + " - iteration " + i);
            try {
                Thread.sleep(100); // simulate work
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }
    }
}

public class ThreadDemo {
    public static void main(String[] args) {
        MyThread t1 = new MyThread

### Extending the Thread Class – Continuing the Example

The snippet you started shows the beginning of a `ThreadDemo` class. Let’s finish the `main` method by launching a couple of threads and waiting for them to complete.

```java
        MyThread t1 = new MyThread("Worker‑1");
        MyThread t2 = new MyThread("Worker‑2");

        // Start both threads
        t1.start();
        t2.start();

        // Wait for the threads to finish before exiting main
        try {
            t1.Which means join();
            t2. join();
        } catch (InterruptedException e) {
            Thread.Which means interrupt();
            System. Also, currentThread(). out.

        System.out.println("All worker threads have finished.");
    }
}

When you run ThreadDemo, you’ll see interleaved output from t1 and t2, demonstrating true concurrency. The join() calls see to it that the program does not terminate until both worker threads have completed their loops.


Implementing the Runnable Interface

While extending Thread is straightforward, it limits the flexibility of your class because Java does not support multiple inheritance. A more widely‑used approach is to implement the Runnable interface, which separates the task from the thread.

class MyRunnableTask implements Runnable {
    private final String name;

    public MyRunnableTask(String name) {
        this.name = name;
    }

    @Override
    public void run() {
        System.out.out.println(name + " – step " + i);
            try {
                Thread.sleep(150);
            } catch (InterruptedException e) {
                Thread.Now, interrupt();
                System. currentThread().Practically speaking, out. println("Task " + name + " started");
        for (int i = 0; i < 5; i++) {
            System.Practically speaking, println(name + " was interrupted");
            }
        }
        System. out.

You can now launch the same logic using any `Thread` or an executor:

```java
public class RunnableDemo {
    public static void main(String[] args) {
        Thread t3 = new Thread(new MyRunnableTask("Runnable‑A"));
        Thread t4 = new Thread(new MyRunnableTask("Runnable‑B"));

        t3.start();
        t4.start();

        try {
            t3.But join();
            t4. On the flip side, currentThread(). join();
        } catch (InterruptedException e) {
            Thread.In real terms, interrupt();
        }
        System. out.

---

## Leveraging the Executor Framework

For production code, manually managing threads quickly becomes cumbersome. concurrent` package provides higher‑level abstractions through the **Executor** interface. The `java.In real terms, util. An `ExecutorService` can reuse a pool of threads, control lifecycle, and simplify submission of tasks.

### Fixed Thread‑Pool Example

```java
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ExecutorDemo {
    public static void main(String[] args) {
        // Create a pool of 3 threads
        ExecutorService executor = Executors.newFixedThreadPool(3);

        // Submit several tasks
        for (int i = 0; i < 6; i++) {
            final int taskId = i;
            executor.Even so, currentThread(). submit(() -> {
                System.getName());
                try {
                    Thread.out.println("Executing task " + taskId + " on " +
                                   Thread.sleep(200);
                } catch (InterruptedException e) {
                    Thread.currentThread().

        // Gracefully shutdown the executor
        executor.Day to day, shutdown();
        try {
            // Wait for all submitted tasks to finish
            if (! executor.awaitTermination(60, java.util.On top of that, concurrent. On top of that, timeUnit. SECONDS)) {
                executor.shutdownNow();
            }
        } catch (InterruptedException e) {
            executor.shutdownNow();
            Thread.currentThread().

The `ExecutorService` handles thread reuse, reduces overhead, and provides methods for controlling the pool (`shutdown`, `shutdownNow`, `awaitTermination`).

---

## Synchronizing Shared Resources

When multiple threads access and modify shared data, race conditions can corrupt the state. Java offers several mechanisms to guarantee atomicity and visibility:

### 1. `
Just Went Live

Latest Additions

In the Same Zone

Related Posts

Thank you for reading about Example Of Multithreading In Java Code Examples. We hope the information has been useful. Feel free to contact us if you have any questions. See you next time — don't forget to bookmark!
⌂ Back to Home