Programming & Development / April 14, 2025

Code Example of Threads in Java

Java threads multithreading example thread class run method thread sleep thread join concurrent programming thread lifecycle thread synchronization Java concurrency

Below is a simple Java code example demonstrating how to create and run multiple threads concurrently. Each thread will print a series of numbers with a short delay to mimic real-world tasks.

Java Code:

java

class NumberPrinter extends Thread {
    private int start;

    public NumberPrinter(int start) {
        this.start = start;
    }

    @Override
    public void run() {
        for (int i = start; i <= start + 5; i++) {
            System.out.println(Thread.currentThread().getName() + ": " + i);
            try {
                Thread.sleep(500); // Simulate delay
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

public class ThreadExample {
    public static void main(String[] args) {
        // Creating thread instances
        NumberPrinter thread1 = new NumberPrinter(1);
        NumberPrinter thread2 = new NumberPrinter(100);

        // Starting threads
        thread1.start();
        thread2.start();

        System.out.println("Main thread continues...");

        // Optional: wait for threads to complete
        try {
            thread1.join();
            thread2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("Main thread finished.");
    }
}

Explanation:

  • Extending Thread: The NumberPrinter class extends Thread and overrides the run() method to define the task.
  • Creating Threads: Two thread objects (thread1, thread2) are created, each printing a different range of numbers.
  • Concurrent Execution: The start() method triggers concurrent execution of both threads.
  • Sleep: Thread.sleep(500) is used to simulate a task delay.
  • Join: join() ensures the main thread waits for other threads to finish before terminating.

This example provides a foundational understanding of how threads work in Java. You can expand on it to include synchronization, Runnable interface, or thread pools as you build more advanced applications.


Comments

No comments yet

Add a new Comment

NUHMAN.COM

Information Technology website for Programming & Development, Web Design & UX/UI, Startups & Innovation, Gadgets & Consumer Tech, Cloud Computing & Enterprise Tech, Cybersecurity, Artificial Intelligence (AI) & Machine Learning (ML), Gaming Technology, Mobile Development, Tech News & Trends, Open Source & Linux, Data Science & Analytics

Categories

Tags

©{" "} Nuhmans.com . All Rights Reserved. Designed by{" "} HTML Codex