Creating Java Threads

by | Dec 18, 2020 | Java

Introduction

In Java Threads can be created in two ways. They are as follows:

  1. Extending the Thread Class
  2. Implementing the Runnable Interface

Thread creation by extending the Thread Class

This process requires you to make a new class that will extend the java.lang.Thread. It will thus override the run () method of the Thread class. To create a new thread thereafter, you will need to create an object of the class and call the start () method on it. This will in turn invoke the run () method on the object and a new thread will be created.

class Sample extends Thread
{
public void run()
{
try
{
System.out.println ("Thread " + Thread.currentThread().getId() + " is running");
} catch (Exception e)
{
System.out.println ("Exception caught");
}
}
}
public class Main_class
{
public static void main(String[] args)
{
int n = 8;
for (int i=0; i<n; i++)
{
Sample obj = new sample();
obj.start();
}
}

 

OUTPUT

Thread 8 is running
Thread 9 is running
Thread 10 is running
Thread 11 is running
Thread 12 is running
Thread 13 is running
Thread 14 is running
Thread 15 is running

 

Thread creation by Runnable Interface

Here the new class will implement java.lang.Runnable. The run() method will again be overridden and an object of the class will be created.

class Runnable_Sample implements Runnable
{
public void run()
{
try
{
System.out.println ("Thread " + Thread.currentThread().getId() + " is running");
} catch (Exception e)
{
System.out.println ("Exception is caught");
}
}
}

class Main_Class
{
public static void main(String[] args)
{
int n = 8;
for (int i=0; i<n; i++)
{
Thread obj = new Thread(new Runnable_Sample ());
obj.start();
}
}
}

 

OUTPUT

Thread 8 is running
Thread 9 is running
Thread 10 is running
Thread 11 is running
Thread 12 is running
Thread 13 is running
Thread 14 is running
Thread 15 is running

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.