MULTITHREADING IN JAVA
Everybody knows about the ability of a human body to many tasks simultaneously, such as hearing talking, digesting and many more. Likewise, a computer with a single processor can create an illusion of current execution of multiple tasks such as playing music, downloading from the internet, sending pages to a printer, copying files from portable drivers while typing in the word processor, it is not actually concurrent execution but it is switching between processes. However, computers with multiple CPus are started coming into the market, which actually execute more than one task at a time. Not only the computer itself does concurrent execution of multiple tasks, almost all modern application and operating system can also performed more than one tasks at a time . Who wants an application that can perform one task at a time or does them one by one? Sometimes it is better to do more than one tasks at a time, instead of doing one task so well. A word processing application such as MS word can do two or more tasks at a time, for instance while formatting the content it can perform a grammer check simultaneously.
Everybody knows about the ability of a human body to many tasks simultaneously, such as hearing talking, digesting and many more. Likewise, a computer with a single processor can create an illusion of current execution of multiple tasks such as playing music, downloading from the internet, sending pages to a printer, copying files from portable drivers while typing in the word processor, it is not actually concurrent execution but it is switching between processes. However, computers with multiple CPus are started coming into the market, which actually execute more than one task at a time. Not only the computer itself does concurrent execution of multiple tasks, almost all modern application and operating system can also performed more than one tasks at a time . Who wants an application that can perform one task at a time or does them one by one? Sometimes it is better to do more than one tasks at a time, instead of doing one task so well. A word processing application such as MS word can do two or more tasks at a time, for instance while formatting the content it can perform a grammer check simultaneously.
Introduction
All modern programmers need to develop applications that can perform many tasks concurrently. Multithreading enables the developer to develop such dynamic applications. All modern computers programming languages support the concept of multithreading. Before getting deeper into the concept, let's understand actually what is a process and thread? A process is nothing but a program in execution. If a program or a process is subdivided into smaller tasks or jobs, each such tasks is called as thread. A single process or a program may have many threads that can run simultaneously and do different tasks at a time. It done to utilize the CPU time we'll. A process of running more than one thread concurrently is known as multithreading. Threads are lightweight sub-processes each thread runs it's own independent execution path and shares common memory space. If one thread trigger an execution, it doesn't effect the other threads which are executing concurrently. The following table differenttiates between multithreading, multi processing and multi tasking.
Multi tasking
It's capacity to run more than one process concurrently in a single CPU environment.
Multi tasking may be process based or thread based
Multithreading
A single process that contains more than one thread (sub-process) running simultaneously is called multithreading
It is a thread based multi tasking
Multiprocessing
It is much like multi tasking done with more than one CPU.
It is a process based multi tasking.
Need for the thread in programming
- To implement parallel processing
- Decreasing the response time of the application
- Utilizing the CPU idle time
- Setting priority to the tasks
- Increasing the processing speed
IN a single thread environment, an exception or i/o request triggered in one thread can cause the entire program to stop or halt. But in a multhreading environment ,one thread can be halted without stopping other thread of the program. IN Java, multithreading is achieved using a Thread class and runnable interface. If the program need to create a thread, it should either extend the thread class or implement the runnabl interface. The Thread class provides many methods to manipulate threads.
Constructors and methods
Thread class in Java. Lange package provides many useful constructors and methods which are used in threads creations.
S. No. Constructor of a Thread class
1. Thread()
2. Thread(string n)
3. Thread(Runnable R)
4. Thread(Runnable r, String S)
The first type of constructor Thread ( ) creates a thread without any parameters, so no values can be passed using this constructor. The second form of the constructor Thread(String n) has one string type variable n to pass the name for the thread while creating an object. The third form of constructor Thread (Runnable r) passes the object of the class which created the thread by implementing the runnable interface. By passing the object of the Thread class, the object of Thread class will be used to manipulate the thread. The final form of thread constructor is used to pass an object of Runnable interface and it's name. The third and last forms of the constructor look more less same, if only runnable object is specified, the third form of constructor is considered otherwise the fourth form of constructor will be considered.
The important methods possessed by the Thread class are the given following maner.
S. No. Methods. Description
1. Run() This method implements the behavior of a thread
2. Start() starts the execution of thread
3. Sleep() stops the execution of thread a specified period of time in. milliseconds
4. Isalive() checks whether the thread is alive or not.
5. Suspend() suspends the thread
6. Resume() resume the thread
7. Stop() stops the thread for execution
8. getpripority() returns of the current priority of thread
9. Setpriority() sets the priority of thread
10. Getname() returns the name of thread
11. Setname() sets the name of thread
12. Interrupt() interrupts the thread
The currentthread() method returns the reference of a thread in which it is invoked. One the reference of thread is recived, it can be controlled program. Demonstrate the manipulation of a main thread.
Example
Public class sample
{
Public static void main (String args[])
{
Thread mt= Thread. CurrentThread();
System. Out. Println(" Default name of current thread is "+Mt);
my. SetName( "mother thread") ;
System. Out. Println("after setting the name of current thread : "+ mt);
String name =Mt. getName();
try
{
System. Out. Println(name+" is started it's execution ");
for(int i=1;i<=10; i++)
{
System. Out. Println("Multithreading in Java ");
Thread. Sleep(2000);
}
System. Out. Println(name+" is completed it's execution ");
}
Catch(Excaption e)
{
System. Out. Println("An exception has been occured: "+e) ;
}
}
Output
Default Name of the current thread is: Thread[main,5maim]
After Setting the Name of the current thread : thread[mother Thread, 5,main]
Mother thread is started it's execution
Multuthreading in Java
Multithreading in Java
Muktithreading in Java
Multithreading in Java
Muktithreading in Java
Multithreading in Java
Multithreading in Java
Multithreading in Java
Multithreading in Java
Muktithreading in Java
Mother thread is completed it's execution
In program , a main thread is referred by invoking the method currebthread() method and reference of current thread is assigned to the Thread object mt. Before setting the name for a current thread, the printkb() method display the following message "Thread[main, 5, main]. The first main is the name of the current thread, 5 is priority and second main is the name of the thread group.
The name of the thread can be changed at any time, to change the name of the current thread, the setName() method of a thread class is called with mother thread as a parameter. In the every next statement, the change the name of the current thread is the retrieving using getName() method and stored in a string type variable name. The change the name of the thread is then display.
The try-catch block is used to handle the Exception, because the sleep() method called in side the try-catch Block may cause the thread to pause for a certain amount of time.
The important methods possessed by the Thread class are the given following maner.
S. No. Methods. Description
1. Run() This method implements the behavior of a thread
2. Start() starts the execution of thread
3. Sleep() stops the execution of thread a specified period of time in. milliseconds
4. Isalive() checks whether the thread is alive or not.
5. Suspend() suspends the thread
6. Resume() resume the thread
7. Stop() stops the thread for execution
8. getpripority() returns of the current priority of thread
9. Setpriority() sets the priority of thread
10. Getname() returns the name of thread
11. Setname() sets the name of thread
12. Interrupt() interrupts the thread
Main thread
Whenever a Java program starts it's execution, a default thread of that program automatically starts execution simultaneously. So what is the Default thread? In Java the execution of a program starts from the class which has the main() function. The class which has a main function is also called as main thread or a default thread. All other threads are called as child thread. The child threads are Instanted and manipulated in the main thread of a program. As a thread the main thread can also be controlled using a thread object. To manipulate the main thread the following methods are using
Syntax: static Thread currentthread()
The currentthread() method returns the reference of a thread in which it is invoked. One the reference of thread is recived, it can be controlled program. Demonstrate the manipulation of a main thread.
Example
Public class sample
{
Public static void main (String args[])
{
Thread mt= Thread. CurrentThread();
System. Out. Println(" Default name of current thread is "+Mt);
my. SetName( "mother thread") ;
System. Out. Println("after setting the name of current thread : "+ mt);
String name =Mt. getName();
try
{
System. Out. Println(name+" is started it's execution ");
for(int i=1;i<=10; i++)
{
System. Out. Println("Multithreading in Java ");
Thread. Sleep(2000);
}
System. Out. Println(name+" is completed it's execution ");
}
Catch(Excaption e)
{
System. Out. Println("An exception has been occured: "+e) ;
}
}
Output
Default Name of the current thread is: Thread[main,5maim]
After Setting the Name of the current thread : thread[mother Thread, 5,main]
Mother thread is started it's execution
Multuthreading in Java
Multithreading in Java
Muktithreading in Java
Multithreading in Java
Muktithreading in Java
Multithreading in Java
Multithreading in Java
Multithreading in Java
Multithreading in Java
Muktithreading in Java
Mother thread is completed it's execution
In program , a main thread is referred by invoking the method currebthread() method and reference of current thread is assigned to the Thread object mt. Before setting the name for a current thread, the printkb() method display the following message "Thread[main, 5, main]. The first main is the name of the current thread, 5 is priority and second main is the name of the thread group.
The name of the thread can be changed at any time, to change the name of the current thread, the setName() method of a thread class is called with mother thread as a parameter. In the every next statement, the change the name of the current thread is the retrieving using getName() method and stored in a string type variable name. The change the name of the thread is then display.
The try-catch block is used to handle the Exception, because the sleep() method called in side the try-catch Block may cause the thread to pause for a certain amount of time.
Thread creation
Java is a multi-thread programming language ;its multithreading capability is supported by the built-in libraries which enable the programmer to develop applications that can support parallel processing. In Java, a thread can be created by the following two ways, using which any class can become a thread.
1. By implementing the Runnable interface
2. By extending the Thread classs
1.by implementing Runnable interface:
The simplest way of creating a thread is by implementing runnable interface. At a time any number of thread can created in a program using a runnable interface. Creating a thread by implementing runnable interface using run() method.
Syntax:
Public class class_name implements Runnable
{
Public void run ()
{
}
}
Example
Class demo implements runnable
{
Public void run ()
{
System.out.println("hrllo");
}
}
Class sample
{
Public static void main (String arg[])
{
Demo d1=new Demo ();
Thread t1= new Thread (d1);
t1. Start();
System. Out. Println("welcome ");
}
}
Output
Welcome
Hello
2. By extends Thread class
The second way to create a thread is by extending a Thread class. The class which extends the thread class will become a sub class. It can be contained in Lang package.
Syntax:
Public class extends Thread class
{
Void run()
{
}
Example
Class A extends Thread
{
Void run ()
{
System. Out. Ptinyln("hello");
}
}
Class B
{
Public static void main (String arg[])
{
A ob=new ob();
Ob. Start();
System. Out. Ptuntln("good morning ");
}
}
Output
Good morning
Hello
choosing a method for thread creation
- if the class needs to inherit more than one class ,it is better to create a thread by implementing the runnable interface.
- if the programmer wants to pass runnable to any other thread pool , then runnnable interface is a good choice.
- if the thread is going use only run() method ,implemented it with the runnable interface .this is because the thread class not only override the run(), it override all the methods in the thread class .
- if the programmer needs to reuse the run(),it is better to opt for the runnable interface.
Example: demonstrates the difference in the use of the thread class and runnable interface for thread creation.
class A implements runnable
{
int n=0;
public void run()
{
n++;
System.out.println("through runnable interface : "+n);
}
}
class B extends Thread
{
int n=0;
public void run()
{
n++;
System.out.println()"through extends thread class :"+ n);
}
}
public class C
{
public static void main(String args[]) throws interrrupetedException
{
A run=new A();
Thread t=new Thread(run);
t.start(();
thread.sleep(1000);
Thread th=new Thread(run);
th.start();
Thred.sleep(1000);
}
}