×

Creation of Multi Thread in java

What are threads in Java?

We can use threads to facilitate parallel processing. Threads are helpful when you wish to execute several pieces of code concurrently.

A thread is a small process that may run numerous pieces of code concurrently. The thread, however, differs from an operation. Each process will have its own memory space allocated in the OS. The same holds true for threads, as they have distinct memory. The same RAM that the process has been allotted will be used to run all the threads.

Thread creation in Java:

Generally, the creation of a thread can be done in two ways in Java.

  • Implementing Runnable interface
  • Extending Thread class

Multi-thread in Java:

Java's multithreading feature allows for the concurrent execution of several threads.

Because threads employ a shared memory space, multithreading is preferred to multiprocessing. They conserve memory by not allocating separate memory areas, and context switching between the threads is quicker than the process.

Animated films and video games are the main uses of Java multithreading.

Multi-thread execution in Java:

MyThreadExample. java

class MyThread implements Runnable
// implementing MyThread class with Runnable interface
// you can define with any class name
{
int n;
MyThread (int n)
{
                 this.n = n;
}
public void run ()
{
                      for (int i = 1; i <= n; i++)
                      { 
                        // creating different thread procedures
                                System.out.println (" Thread One " +i);
// printing thread one
                                if (i%2 == 0)
                                 {
                                 System.out.println ("Even No from Thread Two" +(i*i));
                                 // printing thread two i.e., if “i” is even
// then it prints the square of “i”
                                   }                                 
                                else
                               {
                                 // printing thread three, i.e., the cube of the odd digit
                      System.out.println ("Odd No. from Thread Three " +(i*i*i));
}
                            try
                            {
                             Thread.sleep (500);
       // thread in sleep cycle of 500ms 
// threads execute after 500ms after first thread execution
                           }
                            catch (InterruptedException ie)
                             {
                                      ie.printStackTrace ();
                              }
                     }
}
}
class MyThreadExample 
{
public static void main (String args [])
{
                     MyThread m1 = new MyThread (5);
                      MyThread m2 = new MyThread (5);
// invoking thread class
                      Thread t1 = new Thread (m1);
                      Thread t2 = new Thread (m2);
// creation of thread methods
                      t1.start ();
                      t2.start ();
// implementation of threads


}
 }

Output:

Creation of Multi-Thread in Java

Creating multi -thread by extending thread class:

MyThreadExample.java

class MyThread extends Thread
// implementing MyThread class with extending thread class
// you can define with any class name
{
public void run (int n)
{
                      for (int i = 1; i <= n; i++)
                      { 
                        // creating different thread procedures
                                System.out.println (" Thread One " +i);
// printing thread one
                                if (i%2 == 0)
                                 {
                                 System.out.println ("Even No from Thread Two" +(i*i));
                                 // printing thread two i.e., if “i” is even
// then it prints the square of “i”
                                   }                                 
                                else
                               {
                                 // printing thread three, i.e., the cube of the odd digit
                      System.out.println ("Odd No. from Thread Three " +(i*i*i));
}
                            try
                            {
                             Thread.sleep (500);
       // thread in sleep cycle of 500ms 
// threads execute after 500ms after first thread execution
                           }
                            catch (InterruptedException ie)
                             {
                                      ie.printStackTrace ();
                              }
                     }
}
}
class MyThreadExample 
{
public static void main (String args [])
{
// invoking thread class
                      MyThread t1 = new MyThread ();
                                  t1.run (5);
                      MyThread t2 = new MyThread ();
t2.run (5);
// creation of thread methods
                      t1.start ();
                      t2.start ();
// implementation of threads


}
 }

Output:

Creation of Multi-Thread in Java

Some uses of multithreading:

  • Threads are autonomous, and you can do numerous operations simultaneously; it doesn't block the user.
  • It saves time since numerous operations can be completed simultaneously.
  • Because each thread is autonomous, if an exception arises in one thread, it has no effect on the other threads.

Multitasking:

Executing numerous things at once is known as multitasking. To make use of the CPU, multitasking is used. You can multitask in two different ways:

  • Process-based Task Switching (Multiprocessing)
  • Multiple tasks based on threads (Multithreading)

Process-based Task Switching:

  • Each process has a memory address. In other words, distinct memory space is assigned to each process.
  • A procedure is substantial.
  • Communication between processes has a significant cost.
  • For the purposes of storing and loading registers, memory mappings, updating lists, etc., switching from one process to another takes some time.

Multiple tasks based on threads:

  • The same address space is used by all threads.
  • The threads are lightweight.
  • The thread cost of communication is minimal.

Related Topics

Self-Descriptive Numbers in Java

A number n is given. Identifying the self-descriptive numbers that exist between 1 and n is our task. Self-Descriptive Numbers The definition of a self-descriptive number, m, is a number with b...

6 minutes read.

Java.net.SocketException

Exception The problem occurred during the execution of the program. If an exception occurs in the program, the program gets terminated. To skip the exception occurring statements, we have to handle...

4 minutes read.

Java Math rint() Method

The rint() method of Java Math class returns the double value which is close to the specified argument and is equal to mathematical integer. Syntax: public static double rint(double a) Parameters: The parameter ‘a’...

1 minute read.

Java Programming certification

The most common technology utilized in the creation of applications is Java. People and businesses like it because it turns original ideas into useful software solutions. A Java programming certification can...

6 minutes read.

How to Print array in Java?

A Java array is a data structure that allows us to hold components of the same data type. An array's items are kept in a single memory region. As a...

6 minutes read.

Java Math getExponent() Method

The getExponent() method of Math class returns the unbiased exponent of the argument. Syntax: public static int getExponent (double d) Parameters: The parameter ‘d’ represents the double value. Return Value: The getExponent () method returns the...

1 minute read.

Applet Life Cycle in Java

In this article, we are going to acknowledge you about what a applet is, what is its life cycle and stages in life cycle, along with the syntax and example...

4 minutes read.

Convert List to String in Java

We occasionally need to create a string from a list of characters. Since a string is only a collection of characters, a character array can be converted into a string....

6 minutes read.

Computing Digit Sum of all Numbers from 1 to n in Java

In this tutorial, we will discuss various methods to compute the sum of digits of all numbers beginning from 1 to n through a Java program. We will achieve it through...

7 minutes read.

Java Database Connectivity with MySQL

In this tutorial, we will learn how to connect Database with MySQL in Java. 5 Steps to Connect to the Database in Java Load the driver (or) Register the driver classEstablish a...

4 minutes read.

MVC in Java

A well-known design pattern is Model-View-Controller. The discipline of web development. We can organize our code in this manner. The document stipulates that a program or application must include a...

4 minutes read.

Java Integer parseInt() method

The parseInt() method of Java Integer class parses the CharSequence argument as a signed decimal integer. The second parameter parses the string argument as a signed integer in the radix specified...

2 minutes read.

What is interpreter in Java?

The programming language Java is platform-neutral. Therefore, can use Java on any platform that supports the Java processor. The Piece of software transforms the Java bytecode contained in the class...

5 minutes read.

Tower of Hanoi Program in Java

Tower of Hanoi Program in Java The Tower of Hanoi program in Java is written to solve a mathematical puzzle, called Tower of Hanoi, where we have three poles and n...

4 minutes read.

Java Extends keyword

Extends Extends is a keyword which is completely depended on the concept of the inheritance of the java programming language.To understand about of the keyword, we need to learn the concept...

3 minutes read.

Ad Hoc Problem on Arrays in Java

Ad hoc problems are issues that arise unexpectedly and require immediate attention. These problems can range from small and straightforward issues to more complex and time-consuming problems. Examples of ad...

3 minutes read.

Java Serialization

JAVA SERIALIZATION Serialization is a process by which objects can be represented as a sequence of bytes. These bytes have information about object's data, object's type and datatypes of members in...

3 minutes read.

Java Integer valueOf() method

The valueOf() method of Java Integer class returns an Integer object holding the specified int value. The second method returns an Integer object holding the specified String value. The third syntax returns...

2 minutes read.

Contextual keywords in Java

Contextual keywords were earlier known as restricted identifiers and restricted keywords. Context keywords are chosen based on their expected placement in the syntactic grammar. These are the keywords in the code...

3 minutes read.

Java Database Connectivity with Oracle

JDBC: A Programmer can develop a complete application using the Java built-in API’s. So, for storing the data required for solving a real-world problem is stored into a database. To connect...

5 minutes read.