A Simple Java Thread Example Demonstrating Concurrent Execution

Question

Can someone provide a straightforward Java thread example that illustrates simultaneous execution of multiple threads?

public class ThreadExample {

    public static void main(String[] args) {
        // Create three threads
        Thread t1 = new Thread(new Task("Thread 1"));
        Thread t2 = new Thread(new Task("Thread 2"));
        Thread t3 = new Thread(new Task("Thread 3"));

        // Start the threads
        t1.start();
        t2.start();
        t3.start();
    }
}

class Task implements Runnable {
    private String threadName;

    Task(String name) {
        this.threadName = name;
    }

    @Override
    public void run() {
        for (int i = 1; i <= 5; i++) {
            System.out.println(threadName + " is running iteration " + i);
            try {
                Thread.sleep((int)(Math.random() * 1000)); // Sleep for a random time
            } catch (InterruptedException e) {
                System.out.println(threadName + " interrupted.");
            }
        }
    }
}

Answer

In Java, threading allows multiple threads of execution to run concurrently. This example illustrates the creation of three separate threads, providing a clear demonstration of their simultaneous operation.

public class ThreadExample {

    public static void main(String[] args) {
        // Create three threads
        Thread t1 = new Thread(new Task("Thread 1"));
        Thread t2 = new Thread(new Task("Thread 2"));
        Thread t3 = new Thread(new Task("Thread 3"));

        // Start the threads
        t1.start();
        t2.start();
        t3.start();
    }
}

class Task implements Runnable {
    private String threadName;

    Task(String name) {
        this.threadName = name;
    }

    @Override
    public void run() {
        for (int i = 1; i <= 5; i++) {
            System.out.println(threadName + " is running iteration " + i);
            try {
                Thread.sleep((int)(Math.random() * 1000)); // Sleep for a random time
            } catch (InterruptedException e) {
                System.out.println(threadName + " interrupted.");
            }
        }
    }
}

Causes

  • Threads are independent units of execution and can run concurrently.
  • Java's Thread class and Runnable interface facilitate concurrent execution.

Solutions

  • Define task logic in a runnable class.
  • Instantiate threads with the runnable implementation.
  • Use start() method to launch multiple threads.

Common Mistakes

Mistake: Forgetting to start a thread with start() method, using run() instead.

Solution: Always use start() to initiate thread execution.

Mistake: Incorrectly managing thread lifecycle, leading to deadlocks or resource issues.

Solution: Carefully design thread interactions and utilize concurrency controls where necessary.

Helpers

  • Java threads example
  • Java concurrent execution
  • multithreading in Java
  • Runnable interface Java
  • Java threading tutorial

Related Questions

⦿Where Are Java Preferences Stored on macOS?

Discover where Java preferences are stored on macOS and how they differ from Windows registry storage.

⦿Why Can't I Return Null from a Method That Has an Integer Return Type?

Learn why returning null from a method that expects an int type causes errors. Explore solutions and best practices for handling such scenarios.

⦿How to Use Enums with Android's IntDef Annotations Correctly?

Learn how to utilize enums with IntDef annotations in Android and resolve incompatible type issues.

⦿How to Create Read-Only Fields in Java Accessible for Class Scope?

Learn how to create writable fields within a Java class that are readonly to external classes ensuring encapsulation and data integrity.

⦿How to Preserve Field Annotations in Constructor Parameters Using Lombok?

Learn how to retain field annotations in constructor parameters with Lomboks RequiredArgsConstructor. Comprehensive guide with code examples.

⦿What Are the Benefits of Using JNDI for Data Source Configuration?

Discover the advantages of using JNDI for data sources including connection management resource abstraction and improved maintainability.

⦿Understanding the Functionality of chain.doFilter in the Filter.doFilter Method

Explore the role of chain.doFilter in Javas Filter.doFilter method including its effects and common misconceptions about recursion.

⦿How to Resolve java.lang.ClassNotFoundException: javax.servlet.ServletContext in JUnit Tests

Learn how to fix java.lang.ClassNotFoundException javax.servlet.ServletContext in Spring MVC JUnit tests with this detailed guide and code examples.

⦿Understanding Java Enum Inheritance: Why Enums Cannot Extend Other Enums

Explore why Java enums cannot inherit from other enums. Discover the design principles behind enum restrictions and alternatives for Java developers.

⦿How Can a Thread Return a Value Upon Completion of Its Execution?

Learn how to retrieve a value from a Thread in Java after it finishes execution including code snippets and common pitfalls.

© Copyright 2025 - CodingTechRoom.com