The following program demonstrates How to Create Threads in Java.

Problem Statement

Create an application to show the concept of creating thread through Thread class and Runnable interface.

Solution

Creating threads in Java can be done using both the Thread class and the Runnable interface. Here, I’ll provide you with a simple Java application that demonstrates both approaches. This application will create two threads, one using the Thread class and the other using the Runnable interface, to perform a simple task: printing numbers from 1 to 5.

// Define a class that implements the Runnable interface
class MyRunnable implements Runnable {
    @Override
    public void run() {
        for (int i = 1; i <= 5; i++) {
            System.out.println("Runnable Thread: " + i);
            try {
                Thread.sleep(100); // Sleep for 100 milliseconds
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

public class ThreadExample {
    public static void main(String[] args) {
        // Creating a thread using the Thread class
        Thread thread1 = new Thread() {
            @Override
            public void run() {
                for (int i = 1; i <= 5; i++) {
                    System.out.println("Thread Class Thread: " + i);
                    try {
                        Thread.sleep(100); // Sleep for 100 milliseconds
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        };

        // Creating a thread using the Runnable interface
        Runnable myRunnable = new MyRunnable();
        Thread thread2 = new Thread(myRunnable);

        // Start both threads
        thread1.start();
        thread2.start();
    }
}

In this example, we have defined a class MyRunnable that implements the Runnable interface. It overrides the run() method, where we define the task to be performed by the thread.

In the main method, we create two threads:

  1. One using the Thread class by extending it and overriding the run() method.
  2. The other using the Runnable interface by passing an instance of MyRunnable to the Thread constructor.

Both threads are started using the start() method, and they will run concurrently, printing numbers from 1 to 5 with a 100-millisecond pause between each number.

This example illustrates the two common ways of creating and running threads in Java, using both the Thread class and the Runnable interface.


Further Reading

Spring Framework Practice Problems and Their Solutions

From Google to the World: The Story of Go Programming Language

Why Go? Understanding the Advantages of this Emerging Language

Creating and Executing Simple Programs in Go

20+ Interview Questions on Go Programming Language

Java Practice Exercise

programmingempire

Princites