Creating Threads in Java

Multithreading in Java is a feature that allows concurrent execution of two or more parts of a program to maximize the utilization of the CPU. Each part of such a program is called a thread, and the process of executing multiple threads simultaneously is called multithreading.

Creating Threads in Java

In Java, there are two main ways to create a thread:

  1. By extending the Thread class
  2. By implementing the Runnable interface
Example: Extending the Thread Class

class MyThread extends Thread {
    public void run() {
        for (int i = 0; i < 5; i++) {
            System.out.println(Thread.currentThread().getId() + " Value " + i);
            try {
                Thread.sleep(1000);  // sleep for 1 second
            } catch (InterruptedException e) {
                System.out.println(e);
            }
        }
    }

    public static void main(String[] args) {
        MyThread t1 = new MyThread();
        MyThread t2 = new MyThread();
        t1.start();
        t2.start();
    }
}


Explanation

Extending the Thread class:
  • A class is created that extends Thread.
  • The run() method is overridden to define the code that constitutes the new thread.
  • An instance of the class is created and the start() method is called to begin execution.
Example: Implementing the Runnable Interface

class MyRunnable implements Runnable {
    public void run() {
        for (int i = 0; i < 5; i++) {
            System.out.println(Thread.currentThread().getId() + " Value " + i);
            try {
                Thread.sleep(1000);  // sleep for 1 second
            } catch (InterruptedException e) {
                System.out.println(e);
            }
        }
    }

    public static void main(String[] args) {
        Thread t1 = new Thread(new MyRunnable());
        Thread t2 = new Thread(new MyRunnable());
        t1.start();
        t2.start();
    }
}

Explanation
Implementing the Runnable interface:
  • A class implements the Runnable interface.
  • The run() method is overridden to define the thread's code.
  • An instance of Thread is created, passing the Runnable instance to the Thread constructor.
  • The start() method is called to begin execution.
In both examples, the run() method contains a loop that prints the current thread's ID and a value, then sleeps for one second to simulate a time-consuming task. The start() method is called on each thread to begin their execution

Comments

Popular posts from this blog

Introduction to Java Swing

KTU OOP LAB JAVA CSL 203 BTech CS S3 - Dr Binu V P

JDBC Application Program