This is a very helpful article for IT apriants .
Multithreading in Java
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. So, threads are light-weight processes within a process.
The main purpose of multithreading is to provide simultaneous execution of two or more parts of a program to maximum utilize the CPU time. A multithreaded program contains two or more parts that can run concurrently. Each such part of a program called thread.
Basically multithreading is useful to develop an application in multi programming environment where a single program can do many thing simultaneously .
Threads can be created by using two mechanisms :
- Extending the Thread class
- Implementing the Runnable Interface
Thread creation by extending the Thread class
We create a class that extends the java.lang.Thread class. This class overrides the run() method available in the Thread class. A thread begins its life inside run() method. We create an object of our new class and call start() method to start the execution of a thread. Start() invokes the run() method on the Thread object.
example
class First extends Thread
{
public void run()
{
for(int i=1;i<=100;i++)
System.out.print(” value of i= “+i);
System.out.println(” \nExit from thread first”);
}
}
class Second extends Thread
{
public void run()
{
for(int j=1;j<=100;j++)
System.out.print(” value of j= “+j);
System.out.println(“\n Exit from thread Second”);
}
}
class Third extends Thread
{ int k;
public void run()
{
for(k=1;k<=100;k++)
System.out.print(” value of k= “+k);
System.out.println(“\n Exit from thread Third”);
}
}
class Test
{
public static void main(String args[])
{
First f1=new First();
Second s1=new Second();
Third t1= new Third();
f1.start();
s1.start();
t1.start();
}
}
Thread creation by implementing the Runnable Interface
We create a new class which implements java.lang.Runnable interface and override run() method. Then we instantiate a Thread object and call start() method on this object.
EG.
Class className impliments Runnable
{
Public void Run()
{
}
}
Thanking You
Tech Jitendra
