Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Creating Threads in Java | How to create Thread

Creating threads in Java | We know that every Java program has at least one Thread called main thread. When a program starts, main thread starts running immediately.

Apart from this main thread, we can also create our own threads in a program that is called child thread. Every child threads create from its main thread known as parent thread.

There are two ways to create a new thread in Java. They are as follows:
1. One is by extending java.lang.Thread class
2. Another is by implementing java.lang.Runnable interface

Extending Thread Class in Java


Extending Thread class is the easiest way to create a new thread in Java. The following steps can be followed to create your own thread in Java.
1. Create a class that extends the Thread class. In order to extend a thread, we will use a keyword extends. The Thread class is found in java.lang package. The syntax for creating a new class that extends Thread class is as follows:

Class Myclass extends Thread

2. Now in this newly created class, define a method run(). Here, run() method acts as entry point of the new thread. The run() method contains the actual task that thread will perform. Thus, we override run() method of Thread class.

public void run()
{
 // statements to be executed.
}

3. Create an object of newly created class so that run() method is available for execution. The syntax to create an object of Myclass is as follows:

Myclass obj = new Myclass();

4. Now create an object of Thread class and pass the object reference variable created to the constructor of Thread class.

Thread t = new Thread(obj);
or,
 Thread t = new Thread(obj, "threadname");

5. Run the thread. For this, we need to call to start() method of Thread class because we cannot call run() method directly. The syntax to call start() method is as follows:

t.start();

Now, the thread will start execution on the object of Myclass and statements inside run() method will be executed while calling it. By following all the above steps, you can create a Thread in Java.

Let’s create a program where we will create a new thread. In this program, we will create a class NewThread with run() method. Look at the following source code.

Program source code 1:

public class MyThread extends Thread
{
 public void run()
 {
   System.out.println("New thread running ");
 }
 public static void main(String[] args)
 {
  System.out.println("Main thread running");	 

// Create an object of MyThread class.	 
   MyThread th = new MyThread();

// Create an object of Thread class and pass the object reference variable th.   
   Thread t = new Thread(th);
   
// Now run thread on the object. For this, call start() method using reference variable t.   
   t.start(); // This thread will execute statements inside run() method of MyThread object.
 }
}
Output:
      Main thread running
      New thread running

When you compile and run the above program, you will get similar output.

Explanation:
1. In this example program, we create a class MyThread with run() method. The class MyThread extends Thread class so that we are overriding run() method of Thread class to perform a specific task.

2. We created an object of MyThread class with reference variable th so that run() is available for execution.
3. Now, we created an object of Thread class and passes the reference variable th as an argument to its constructor.

4. When JVM executes t.start(); then start() method is called. A new thread will create from the main thread and starts executing the code inside run() method. In run() method, we wrote code to print a statement on the console.

The most important thing to realize that the main thread and new thread are two separate processes and are not executed sequentially. This is because we created and started a new thread from main thread.

It does not mean that new thread will execute first and then return to main thread. Here, two different tasks are performing one by one by two independently threads under the same program environment.

Let’s create a program where we will check when a new thread creates on the basis of active number of threads.

Program source code 2:

public class NewThread extends Thread {
public 	void run()
{
 Thread th1 = Thread.currentThread();
 System.out.println(th1); 
  System.out.println("New thread strats running");
  System.out.println("I am in run() method");
}
public static void main(String[] args)
{
 System.out.println("Main thread starts running");	
 Thread ct1 = Thread.currentThread();
 System.out.println(ct1);
 
  int ac1 = Thread.activeCount();
  System.out.println(ac1);  

// Create an object of NewThread class.
   NewThread nt = new NewThread();
   int ac2 = Thread.activeCount();
   System.out.println(ac2);

// Create an object of Thread class and pass the object reference variable nt.
   Thread t = new Thread(nt);
   int ac3 = Thread.activeCount();
   System.out.println(ac3);

// Now run thread on the object. For this, call start() method using reference variable t.
   t.start(); // This thread will execute statements inside run() method of NewThread object.
   int ac4 = Thread.activeCount();
   System.out.println(ac4);
   t.setName("NewThread"); // Setting a new name of thread.
 }
}
Output:
      Main thread starts running
      Thread[main,5,main]
      1
      1
      1
      2
      Thread[NewThread,5,main]
      New thread strats running
      I am in run() method

Explanation:

1. In this example program, you can observe output that when JVM executes t.start() method then the number of active threads becomes 2 that shows that when the start() method is called, a new thread is created. Before it, number of active thread is one.

2. When JVM execute Thread.currentThread(); in the run() method, it will show name of current thread running in the run() method. Therefore, the output will print “Thread[NewThread,5,main]”.

Creating Threads in Java using Runnable Interface


Threads can also be created by implementing Runnable interface of java.land package. Creating a thread by implementing Runnable interface is very similar to creating a thread by extending Thread class.

All steps are similar for creating a thread by implementing Runnable interface except the first step. The first step is as follows:

1. To create a new thread using this method, create a class that implements Runnable interface of java.lang package. The syntax for creating a new class that implements Runnable interface is as follows:

class Myclass implements Runnable

Let’s write a program to create a new thread by implementing Runnable interface.

Program source code 3:

public class MyThread implements Runnable
{
 public void run()
 {
  System.out.println("New thread running ");
  for(int i = 1; i 
Output:
       Main thread running
       New thread running 
        1
        2
        3
        4
        5
       Thread[Thread-0,5,main]

Explanation:

When the start() method of Thread class is called using reference variable t, the thread will start execution on the object of MyThread. In that object, start() method calls run() method and executes statements inside the run() method. Whenever the execution of run() method stops, execution of thread also stops.

Multitasking with single Thread in Java


In all the previous example programs, you will have noticed that one thread executes only one task at a time. But we can also execute multiple tasks from a single thread.

For example, suppose there are three tasks to be executed in a program. For this purpose, we will create a thread and pass 3 tasks one by one to the thread.

We will write code separately in separate methods such as task1, task2, and task3 for all these tasks. Then, all these methods will call from run() method one by one.

Let’s take an example program based on performing multiple tasks with a single thread.

Program source code 4:

public class MyThread implements Runnable
{
 int a = 20, b = 10;	
public void run()
{
 addition(); // task1
 subtraction(); // task2
 multiplication(); // task3
}
void addition()
{
 int sum = a + b;
 System.out.println("Addition of two numbers: " +sum);
}
void subtraction()
{
 int sub = a - b;
 System.out.println("Subtraction of two numbers: " +sub);
}
void multiplication()
{
 int multiply = a * b;
 System.out.println("Multiplication of two numbers: " +multiply);
}
public static void main(String[] args)
{
 System.out.println("Main thread running");	 
 
  MyThread th = new MyThread();   
  Thread t = new Thread(th);
  t.start(); // This thread will execute statements inside run() method of MyThread object.
  }
}
Output:
       Main thread running
       Addition of two numbers: 30
       Subtraction of two numbers: 10
       Multiplication of two numbers: 200

In this example program, a single thread t is used to execute three tasks one by one.

Note that at a time, a thread executes only one method inside the run() method. It can never execute other methods unless they are called from run() method.

Final words
Extending Thread class and implementing Runnable interface for creating threads in Java are functionally same. But there is one disadvantage of creating threads in Java using extending Thread class.

When you extend Thread class, there is no scope to extend another class because multiple inheritance is not supported by Java.
For example, class Myclass extends Thread, AnotherClass // Invalid

But if you implement Runnable interface for creating a thread, still there is scope to extend another class. So, implementing Runnable interface for creating a new thread has an advantage for programmers.

For example, class Myclass extends AnotherClass implements Runnable // Valid.
Thanks for reading!!!

The post Creating Threads in Java | How to create Thread appeared first on Scientech Easy.



This post first appeared on Scientech Easy, please read the originial post: here

Share the post

Creating Threads in Java | How to create Thread

×

Subscribe to Scientech Easy

Get updates delivered right to your inbox!

Thank you for your subscription

×