Multi Threading
Multi Threading
KALASH JAIN
CS-6B
Threads
• Threads are lightweight processes as the
overhead of switching between threads is less
• The Java Virtual Machine creates a thread
when your program is run called the Main
Thread
Why do we need threads?
• To enhance parallel processing
• To increase response to the user
• To utilize the idle time of the CPU
• Prioritize your work depending on priority
Example
• Consider a simple web server
• The web server listens for request and serves it
• If the web server was not multithreaded, the
requests processing would be in a queue, thus
increasing the response time and also might hang
the server if there was a bad request.
• By implementing in a multithreaded
environment, the web server can serve multiple
request simultaneously thus improving response
time.
Creating threads
• In java threads can be created by extending
the Thread class or implementing the
Runnable Interface
• It is more preferred to implement the
Runnable Interface so that we can extend
properties from other classes
• Implement the run() method which is the
starting point for thread execution
Running threads
• Example
class mythread implements Runnable{
public void run(){
System.out.println(“Thread Started”);
}
}
class mainclass {
public static void main(String args[]){
Thread t = new Thread(new mythread()); // This is the way to instantiate a
thread implementing runnable interface
t.start(); // starts the thread by running the run method
}
}
• run() does not start a thread
• Creating an object does not create a thread, calling start() method creates
the thread.
Synchronization
• Synchronization is to prevent data corruption
• Synchronization allows only one thread to
perform an operation on a object at a time.
• If multiple threads require an access to an
object, synchronization helps in maintaining
consistency.
Example
public class Counter{
private int count = 0;
public int getCount(){
return count;
}
}
System.out.println(“Iam in this “);
notifyAll();
}
• The synchronized keyword locks the object. The wait keyword waits
for the lock to be acquired, if the object was already locked by
another thread. Notifyall() notifies other threads that the lock is about
to be released by the current thread.
• Another method notify() is available for use, which wakes up only the
next thread which is in queue for the object, notifyall() wakes up all
the threads and transfers the lock to another thread having the
highest priority.