Login
Your Email
Pasword
Home
Write
Trending
History
Liked
Dashboard

What is Multithreading in Java and how to create threads?

Multithreading provide simultaneous execution of two or more parts of a program to maximum utilize the CPU time.

Do you have similar website/ Product?
Show in this page just for only $2 (for a month)
Create an Ad
0/60
0/180
Multithreading is a Java feature that allows concurrent execution of two or more parts of a program for maximum utilization of CPU. Each part of such program is called a thread. Threads are  the light-weight processes within a process. 
To create threads use two mechanisms : 
1. Extending the Thread class 
2. Implementing the Runnable Interface
Extending the Thread class 
Creation of a class that extends the java.lang.Thread class. 
It overrides the run() method available in the Thread class. A thread begins its life inside run() method. Object is created for new class and call start() method to start the execution of a thread. Start() invokes the run() method on the Thread object. 
class MultithreadingTest extends Thread
 {
 public void run()
 {
 try
 { 
 System.out.println ("Thread " + Thread.currentThread().getId() + " is running");
 }
 catch (Exception e)
 { 
 System.out.println ("Exception is caught");
 }
 }
}
{
 public static void main(String[] args)
 {
 int n = 8;
for (int i=0; i<8; i++)
{
 MultithreadingTest object = new MultithreadingTest();
 object.start();
 }
 }
 }
Implementing the Runnable Interface
Creation of a new class which implements java.lang.Runnable interface and override run() method. Then  instantiate a Thread object and call start() method on this object.
class MultithreadingTest implements Runnable
{
 public void run()
 {
 try
 {
System.out.println ("Thread " + Thread.currentThread().getId() + " is in running form"); }
 catch (Exception e)
 {
System.out.println ("Exception is caught");
 }
 }

 class Multithread
{
 public static void main(String[] args)
 {
 int n = 8; 
 for (int i=0; i<8; i++)
 {
 Thread object = new Thread(new MultithreadingTest()); object.start();
 }
 }
Run these codes on IDE to check the output.
Extending the Thread class  cannot extends any other class because Java doesn?t support multiple inheritance.
CONTINUE READING
Multithreading
Java
Threads Creation
Ayesha
Tech writer at newsandstory