 Multithreading is similar to multi-processing.
 A multi-processing Operating System can run several processes at the same time
 Each process has its own address/memory space
 The OS's scheduler decides when each process is executed
 Only one process is actually executing at any given time. However, the system appears to be
running several programs simultaneously
 Separate processes to not have access to each other's memory space
 Many OSes have a shared memory system so that processes can share memory space
 In a multithreaded application, there are several points of execution within the same memory space.
 Each point of execution is called a thread
 Threads share access to memory
 In a single threaded application, one thread of execution must do everything
 If an application has several tasks to perform, those tasks will be performed when the thread
can get to them.
 A single task which requires a lot of processing can make the entire application appear to be
"sluggish" or unresponsive.
 In a multithreaded application, each task can be performed by a separate thread
 If one thread is executing a long process, it does not make the entire application wait for it
to finish.
 If a multithreaded application is being executed on a system that has multiple processors, the OS may
execute separate threads simultaneously on separate processors.
 Threads can be in one of four states
 Created, Running, Blocked, and Dead
 A thread's state changes based on:
 Control methods such as start, sleep, yield, wait, notify
 Termination of the run method
Created Runnable Blocked
Dead
start()Thread()
run() method terminates
sleep()
wait()
notify()
 The thread class has a run() method
 run() is executed when the thread's start() method is invoked
 The thread terminates if the run method terminates
 To prevent a thread from terminating, the run method must not end
 run methods often have an endless loop to prevent thread termination
 One thread starts another by calling its start method
 The sequence of events can be confusing to those more familiar with a single threaded
model.
Thread1
Thread Object
start() Thread2
run()
 The obvious way to create your own threads is to subclass the Thread class and then override the run() method
 This is the easiest way to do it
 It is not the recommended way to do it.
 Because threads are usually associated with a task, the object which provides the run method is usually a subclass of some
other class
 If it inherits from another class, it cannot inherit from Thread.
 The solution is provided by an interface called Runnable.
 Runnable defines one method - public void run()
 One of the Thread classes constructor takes a reference to a Runnable object
 When the thread is started, it invokes the run method in the runnable object instead of its own run method.
 In the example below, when the Thread object is instantiated, it is passed a reference to a
"Runnable" object
 The Runnable object must implement a method called "run"
 When the thread object receives a start message, it checks to see if it has a reference to a
Runnable object:
 If it does, it runs the "run" method of that object
 If not, it runs its own "run" method
Thread1
Thread Object
start() Thread2
run()
Runnable Object
run()
Runnable Object
public class Test implements Runnable
{
private Thread theThread;
public void start()
{
if (theThread == null)
{
theThread = new Thread(this);
theThread.start();
}
}
public void run()
{
// This method runs in its
// own thread
}
Thread1
Thread Object
start()
Thread2
run() run()
start()Thread(Runnable)
 In Java 1.1, the Thread class had a stop() method
 One thread could terminate another by invoking its stop() method.
 However, using stop() could lead to deadlocks
 The stop() method is now deprecated. DO NOT use the stop method to terminate a
thread
 The correct way to stop a thread is to have the run method terminate
 Add a boolean variable which indicates whether the thread should continue or not
 Provide a set method for that variable which can be invoked by another thread
 Threads are lightweight processes as the overhead of switching between threads is
less
 The can be easily spawned
 The Java Virtual Machine spawns a thread when your program is run called the Main
Thread
 To enhance parallel processing
 To increase response to the user
 To utilize the idle time of the CPU
 Prioritize your work depending on priority
 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
 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
 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
}
}
 Calling t.run() does not start a thread, it is just a simple method call.
 Creating an object does not create a thread, calling start() method creates the thread.
 The previous example illustrates a Runnable class which creates its own thread when
the start method is invoked.
 If one wished to create multiple threads, one could simple create multiple instances
of the Runnable class and send each object a start message
 Each instance would create its own thread object
 Is the a maximum number of threads which can be created?
 There is no defined maximum in Java.
 If the VM is delegating threads to the OS, then this is platform dependent.
 A good rule of thumb for maximum thread count is to allow 2Mb of ram for each
thread
 Although threads share the same memory space, this can be a reasonable
estimate of how many threads your machine can handle.
 Every thread is assigned a priority (between 1 and 10)
 The default is 5
 The higher the number, the higher the priority
 Can be set with setPriority(int aPriority)
 The standard mode of operation is that the scheduler executes threads with higher priorities first.
 This simple scheduling algorithm can cause problems. Specifically, one high priority thread can
become a "CPU hog".
 A thread using vast amounts of CPU can share CPU time with other threads by invoking the yield()
method on itself.
 Most OSes do not employ a scheduling algorithm as simple as this one
 Most modern OSes have thread aging
 The more CPU a thread receives, the lower its priority becomes
 The more a thread waits for the CPU, the higher its priority becomes
 Because of thread aging, the effect of setting a thread's priority is dependent on the platform
 Sometimes a thread can determine that it has nothing to do
 Sometimes the system can determine this. ie. waiting for I/O
 When a thread has nothing to do, it should not use CPU
 This is called a busy-wait.
 Threads in busy-wait are busy using up the CPU doing nothing.
 Often, threads in busy-wait are continually checking a flag to see if there is anything to
do.
 It is worthwhile to run a CPU monitor program on your desktop
 You can see that a thread is in busy-wait when the CPU monitor goes up (usually to 100%), but
the application doesn't seem to be doing anything.
 Threads in busy-wait should be moved from the Run queue to the Wait queue so that they do not hog
the CPU
 Use yield() or sleep(time)
 Yield simply tells the scheduler to schedule another thread
 Sleep guarantees that this thread will remain in the wait queue for the specified number of
milliseconds.
 Those familiar with databases will understand that concurrent access to data can lead to data
integrity problems
 Specifically, if two sources attempt to update the same data at the same time, the result of the
data can be undefined.
 The outcome is determined by how the scheduler schedules the two sources.
 Since the schedulers activities cannot be predicted, the outcome cannot be predicted
 Databases deal with this mechanism through "locking"
 If a source is going to update a table or record, it can lock the table or record until such time
that the data has been successfully updated.
 While locked, all access is blocked except to the source which holds the lock.
 Java has the equivalent mechanism. It is called synchronization
 Java has a keyword called synchronized
In Java, every object has a lock
To obtain the lock, you must synchronize with the object
The simplest way to use synchronization is by declaring one or more methods to be synchronized
When a synchronized method is invoked, the calling thread attempts to obtain the lock on the
object.
if it cannot obtain the lock, the thread goes to sleep until the lock becomes available
Once the lock is obtained, no other thread can obtain the lock until it is released. ie, the
synchronized method terminates
When a thread is within a synchronized method, it knows that no other synchronized method can
be invoked by any other thread
Therefore, it is within synchronized methods that critical data is updated
 If an object contains data which may be updated from multiple thread sources, the
object should be implemented in a thread-safe manner
 All access to critical data should only be provided through synchronized methods
(or synchronized blocks).
 In this way, we are guaranteed that the data will be updated by only one thread
at a time.
public class SavingsAccount
{
private float balance;
public synchronized void withdraw(float
anAmount)
{
if ((anAmount>0.0) &&
(anAmount<=balance))
balance = balance - anAmount;
}
 However, there is an overhead associated with synchronization
 Many threads may be waiting to gain access to one of the object's synchronized
methods
 The object remains locked as long as a thread is within a synchronized method.
 Ideally, the method should be kept as short as possible.
 Another solution is to provide synchronization on a block of code instead of the
entire method
 In this case, the object's lock is only held for the time that the thread is
within the block.
 The intent is that we only lock the region of code which requires access to the
critical data. Any other code within the method can occur without the lock.
 In high load situations where multiple threads are attempting to access critical
data, this is by far a much better implementation.
 Synchronization is 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.
public class Counter{
private int count = 0;
public int getCount(){
return count;
}
public setCount(int count){
this.count = count;
}
}
 In this example, the counter tells how many an access has been made.
 If a thread is accessing setCount and updating count and another thread is accessing getCount at
the same time, there will be inconsistency in the value of count.
public class Counter{
private static int count = 0;
public synchronized int getCount(){
return count;
}
public synchoronized setCount(int count){
this.count = count;
}
}
 By adding the synchronized keyword we make sure that when one thread is in the setCount method the
other threads are all in waiting state.
 The synchronized keyword places a lock on the object, and hence locks all the other methods which
have the keyword synchronized. The lock does not lock the methods without the keyword synchronized
and hence they are open to access by other threads.
public class Counter{
private int count = 0;
public static synchronized int getCount(){
return count;
}
public static synchronized setCount(int count){
this.count = count;
}
}
 In this example the methods are static and hence are associated with the class object and not
the instance.
 Hence the lock is placed on the class object that is, Counter.class object and not on the
object itself. Any other non static synchronized methods are still available for access by
other threads.
public class Counter{
private int count = 0;
public static synchronized int getCount(){
return count;
}
public synchronized setCount(int count){
this.count = count;
}
}
 The common mistake here is one method is static synchronized and another method is non static
synchronized.
 This makes a difference as locks are placed on two different objects. The class object and the
instance and hence two different threads can access the methods simultaneously.
 The object can be explicitly locked in this way
synchronized(myInstance){
try{
wait();
}catch(InterruptedException ex){
}
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.
Deadlock describes a situation where
two or more threads are blocked
forever, waiting for each
other. Deadlocks can occur
in Java when the synchronized keyword
causes the executing thread to block
while waiting to get the lock,
associated with the specified object.
Method Description
 public void wait()  Causes the current
thread to wait until
another thread invokes
the notify().
 public void notify()  Wakes up a single thread
that is waiting on this
object's monitor.
 public void notifyAll()  Wakes up all the threads
that called wait( ) on the
same object.
 Interthread communication is
all about two threads
communicating with each
other.
 Inter-thread communication)
is a mechanism in which a
thread is paused running in its
critical section and another
thread is allowed to enter (or
lock) in the same critical
section to be executed.It is
implemented by following
methods of Object class:
 wait()
 notify()
 notifyAll()