×

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

Add numbers represented by Linked Lists in Java

For calculating the sum of the two numbers that are represented by a linked list, and then store the result in a new linked list. A linked list's head node...

7 minutes read.

Java Snippets

The term "snippet" refers to a section of code that addresses numerous issues with just a few lines of code. Decreases the number of lines of code and improves programmer...

3 minutes read.

if-else Program in Java

if-else Program in Java The if-else program in Java controls which code snippet will execute. The if-else program is very basic and yet very important. Because it checks how well one...

19 minutes read.

Java Integer toBinaryString() method

The toBinaryString() method of Java Integer class returns a string representing the specified int argument as an unsigned integer in base 2. Syntax public static String toBinaryString (int  i)  Parameters The parameter ‘i’ represents...

1 minute read.

Static class in Java

In Java, a class is a file containing the Java byte code. It can essentially specifically be executed on the JVM (Java Virtual Machine), fairly significant. The JVM is mostly...

7 minutes read.

Java For Keyword

For as a keyword in java: When we need to run a set of statements repeatedly in Java, we use loops. The Java for loop offers a clear way to express...

4 minutes read.

Java Code Optimization

We encounter the idea of optimization while working on any Java application. It is essential that the code we write is not only clear and error-free but also optimized, meaning...

9 minutes read.

Hello Program in Java

Hello Program in Java The Hello program in Java displays the word Hello on the console. It is the basic program in Java. In this section, we will learn different ways...

3 minutes read.

Equidigital in Java

In this section, we will understand what is an equidigital number and how to write Java programs to locate them. It is commonly asked in academic settings and Java coding...

4 minutes read.

Java Class Name

How to write a class name? The following considerations should be made while writing class names. The name of the current class shouldn't be based on a preset or existing class. Java keywords...

3 minutes read.

Java BLOB

The two data types used in Java to store binary and big-character objects are BLOB and CLOB. In contrast to other types of data like float, int, double, etc., it...

4 minutes read.

Java Boolean logicalOr() Method

The logicalOr() method of Java Boolean class returns the result of implementing logical OR operation on the specified Boolean operands. Syntax: public static boolean logicalOr (boolean a, boolean b) Parameters: The parameters ‘a’ and...

2 minutes read.

Knapsack problem in Java

We have a collection of items in the knapsack problem. Every object has a weight and a value. These things should go in a knapsack. But there is a weight...

3 minutes read.

How to create array of objects in Java

Java is an object-oriented programming language therefore everything in Java is based on objects and classes. Array is a data structure that holds data of similar type and dynamically creates...

4 minutes read.

Program to Find the Common Elements between two Arrays in Java

In this article, we are going to learn how to find the common elements between two arrays using Java. Here, we use different approaches in Java to find the common...

3 minutes read.

Interfaces and Classes in Strings in Java

CharBuffer: CharBuffer is utilized to implement the CharSequence interface. With the help of the mentioned class, we can allow character buffers to be utilized instead of CharSequences. We can consider the illustration...

4 minutes read.

Memory Areas in Java

Let’s have a look at how memory management in Java works. We will be going to discuss how the objects get destroyed, the working of a garbage collector, and things...

5 minutes read.

What is String in Java?

What is String in Java? Strings are a collection of characters that are commonly used in Java programming. Strings are regarded as objects in the Java programming language. “String” is a Java...

4 minutes read.

Java Long Keyword

Long is a primitive data type in Java. To initilize variables, we implement the long keyword. It can also be applied to techniques. A 64-bit two's complement integer can put...

3 minutes read.

Zigzag Array in Java

In this tutorial, we discuss, what is zigzag array and its example. Even we will create the java program. In this program, we convert the simple array into a zigzag...

4 minutes read.