Docstoc

Multithreading

Document Sample
Multithreading Powered By Docstoc
					Multithreading
 A thread is a single sequential flow of control within a program.
 Thread does not have its own address space but uses the
  memory and other resources of the process in which it
  executes. There may be several threads in one process.
 The Java Virtual Machine (JVM) manages these and schedules
  them for execution.
 The time needed to perform a context switch from one thread to
  another is substantially less than that required for performing
  such a change between processes.
 Multithreading is a conceptual programming paradigm where a
  program (process) is divided into two or more subprograms
  (process), which can be implemented at the same time in
  parallel. For ex, one subprogram can display an animation on
  the screen while another may build the next animation to be
  displayed. This is something similar to dividing a task into
  subtasks and assigning them to different people for execution
  independently and simultaneously.
 A thread is similar to a program that has a single flow
  of control. It has a beginning, a body, and an end, and
  executes command sequentially. In fact, all main
  programs that we did can be called single threaded
  programs. Every program has at least one thread.
 Java enables us to use multiple flows of control in
  developing programs. Each flow of control may be
  thought of as a separate tiny program known as a
  thread that runs in parallel to others.
 A program that contains multiple flow of control is
  known as multithreaded program.
 Suppose in a java program with four threads, one
  main and three others. The main thread is actually the
  main method module, which is designed to create and
  start the other three threads, namely A,B,C.
 Once initiated by the main thread, the threads A,B,
  and C run concurrently and share the resource jointly.
 The ability of a language to support multithreads is referred to
  as concurrency. Since threads in java are subprograms of a
  main application program and share the same memory space,
  they are known as lightweight threads or lightweight processes.
 „threads running in parallel‟ does not really mean that they
  actually run at the same time. Since all the threads are running
  on a single processor, the flow of execution is shared between
  the threads. The java interpreter handles the switching of
  control between the threads in such a way that it appears they
  are running concurrently.
 Multithreading enables programmers to do multiple things at
  one time. They can divide a long program into threads and
  execute them in parallel. For ex, we can send tasks such as
  printing into the background and continue to perform some
  other task in the foreground. This approach would considerably
  improve the speed of our programs.
 Threads are extensively used in java-enabled browser such as
  HotJava. These browsers can download a file to the local
  computer, display a web page in the window, output another
  web page to a printer and so on.
             Thread Life Cycle
 During the life time of a thread, there are
  many states it can enter. They include:
  1.   Newborn state
  2.   Runnable state
  3.   Running state
  4.   Blocked state
  5.   Dead state
 A thread is always in one of these 5 states. It
  can move from one state to another via a
  variety of ways as shown in fig.
             1. Newborn state
When we create a thread object, the thread is
 born and is said to be in newborn state. The
 thread is not yet scheduled for running. At this
 state, we can do only one of the following with
 it:
  Schedule it for running using start() method.
  Kill it using stop() method
If scheduled, it moves to the runnable state. If
 we attempt to use any other method at this
 stage, an exception will be thrown.
       2. Runnable state (start())
 The runnable state means that the thread is ready for
  execution and is waiting for the availability of the
  processor.
 That is, the thread has joined the queue of threads
  that are waiting for execution.
 If all threads have equal priority, then they are given
  time slots for execution in round robin fashion. i.e.
  first-come, first-serve manner.
 The thread that relinquishes control joins the queue at
  the end and again waits for its turn. This process of
  assigning time to threads is known as time-slicing.
 If we want a thread to relinquish control to another
  thread of equal priority before its turn comes, we can
  do so by using the yield() method.
            3. Running State
Running means that the processor has given its
 time to the thread for its execution.
The thread runs until it relinquishes control on
 its own or it is preempted by a higher priority
 thread.
A running thread may relinquish its control in
 one of the following situations:
1. It has been suspended using suspend() method. A
   suspended thread can be revived by using the
   resume() method. This approach is useful when we
   want to suspend a thread for some time due to
   certain reason, but do not want to kill it.
2. It has been made to sleep. We can put a thread to
   sleep for a specified time period using the method
   sleep (time), where time is in milliseconds. This
   means that the thread is out of the queue during this
   time period. The thread re-enter the runnable state
   as soon as this time period is elapsed.
3. It has been told to wait until some event occurs. This
   is done using the wait() method. The thread can be
   scheduled to run again using the notify() method.
             4. Blocked State
A thread is said to be blocked when it is
 prevented form entering into the runnable state
 and subsequently the running state.
This happens when the thread is suspended,
 sleeping, or waiting in order to satisfy certain
 requirements.
A blocked thread is considered “ not runnable”
 but not dead and therefore fully qualified to run
 again.
                5. Dead State
A running thread ends its life when is has
 completed executing its run() method. It is a
 natural death.
However, we can kill it by sending the stop
 message to it at any state thus causing a
 premature death to it.
A thread can be killed as soon it is born, or
 while it is running, or even when it is in “not
 runnable” (blocked) condition.
• The join method allows one thread to wait for the
  completion of another. If t is a Thread object
  whose thread is currently executing, t.join();
  causes the current thread to pause execution
  until t's thread terminates. Overloads of join
  allow the programmer to specify a waiting
  period. However, as with sleep, join is
  dependent on the OS for timing, so you should
  not assume that join will wait exactly as long as
  you specify. Like sleep, join responds to an
  interrupt by exiting with an InterruptedException.
            Creating Threads
 Thread class in the java.lang package allows
   you to create and manage threads. Each
   thread is a separate instance of this class.
 A new thread can be created in two ways:
1. by extending a thread class
  – Define a class that extends Thread class and
    override its run() method with the code required by
    the thread.
2. by implementing an interface
  – Define a class that implements Runnable
    interface. The Runnable interface has only one
    method, run(), that is to be defined in the method
    with the code to be executed by the thread.
      Extending the Thread class
 We can directly extend the Thread class
class Threadx extends Thread
{
   public void run()
   {
       //logic for the thread
   }
}
 The class ThreadX extends Thread. The logic for the
  thread is contained in the run() method. That method
  may be ery simple or cmplex. It can create other
  objects or even initiate other threads.
 The program can start an instance of the thread by
  using the form shown here:
   – ThreadX tx= new ThreadX();
   – Tx.start();
   – newA().start();//we can write it like this also
The first line instantiates the ThreadX class.
 The second line invokes the start() method of
 that object to start the thread executing. One of
 the actions of the start() method is to invoke the
 run() method. It is possible to create and start
 several instances of ThreadX that execute
 concurrently.
    Another way to create a thread
Declare a class that implements the Runnable
 interface. This method declares only one
 method as shown here:
 public void run();

 class RunnableY implements Runnable
 {
    Public vod run()
    {
        // logic for thread
    }
 }
The application can start an instance of the
 thread by using the following code:
  RunnableY ry = new RunnableY();
  ThreadY ty= new Thread(ry);
  Ty.start();
1st line instantiate the RunnableY class.
2nd line instantiate the Thread class. A
 reference to the RunnableY object is provided
 as the argument to the constructor.
Last line starts the thread.
            Stopping a Thread
Whenever we want to stop a thread form
 running further, we may do so by calling its
 stop() method like:
 ty.stop();
This statement causes the thread to move to
 the dead state. A thread will also move to the
 dead state. A thread will also move to the dead
 state automatically when it reaches the end of
 its method.
The stop() method may be used when the
 premature death of a thread is desired.
                Blocking a Thread
 A thread can also be temporarily suspended or
  blocked form entering into the runnable and
  subsequently running state by using either of the
  following thread methods:
  – Sleep() – blocked for a specified time.
  – Suspend() – blocked until further orders.
  – Wait() – blocked until certain condition occurs.
 These methods cause the thread to go into the
  blocked state. The thread will return to the runnable
  state when the specified time is elapsed in the case of
  sleep(), the resume() method is invoked in the case of
  suspend(), and the notify() method is called in the
  case of wait().
                Thread class
Some of the constructors for Thread are as
 follows:
  – Thread()
  – Thread(Runnable r)
  – Thread(Runnable r, String s)
  – Thread(String s)
Here, r is a reference to an object that
 implements the Runnable interface and s is a
 String used to identify the thread.
       Methods of Thread class
• Method                           Description
• Thread currentThread()           returns a reference to
                                   the current thread
• Void sleep(long msec)             causes the current
• Throws InterruptedException      thread to wait for
  msec milliseconds
• Void sleep(long msec, int nsec) causes the current
  thread to wait for msec milliseconds
• Throws InterruptedException              plus nsec
  nanoseconds
• Void yield()                       causes the current
  thread to yield control of the processor
• to other threads
• String getName()                     returns the name of
  the thread.
• Int getPriority()             returns the priority of the
  thread
• Boolean isAlive()                    returns true if this
  thread has been started and has not
•                               Yet died. Otherwise,
  returns false.
• Void join()                          causes the caller to
  wait until this thread dies.
• Throws InterruptedException
• Void join(long msec)                 causes the caller to
  wait a max of msec until this thread dies.
• Throws InterruptedException                if msec is zero,
  there is no limit for the wait time.
• Void join(long msec, int nsec) causes the caller to
  wait a max of msec plus nsec until this thread
• Throws Interruptedexception                dies. If msec
  plus nsec is zero, there is no limit for the wait time.
• Void run()      comprises the body of the thread. This
  method is overridden by subclasses.
• Void setName(String s)       sets the name of this
  thread to s.
• Void setPriority(int p)sets the priority of this thread to
  p.
• Void start()    starts the thread
• String toString()      Returns the string equivalent of
  this thread.
             Thread Priority
• In java, each thread is assigned a priority,
  which affects the order in which it is scheduled
  for running.
• The threads of the same priority are given equal
  treatment by the Java scheduler and therefore,
  they share the processor on a first-come, first-
  serve basis.
• Java permits us to set the priority of a thread
  using the setPriority() method as follows:
  ThreadName.setPriority(intNumber);
• The intNumber may assume one of these
  constants or any value between 1 and 10.
• The intNumber is an integer value to which the
  thread‟s priority is set. The Thread class defines
  several priority constants:
  – MIN_PRIORITY=1
  – NORM_PRIORITY=5
  – MAX_PRIORITY=10
• The default setting is NORM_PRIORITY.
            Synchronization
When two or more threads need access to a
 shared resource, they need some way to
 ensure that the resource will be used by only
 one thread at a time. The process by which this
 is achieved is called synchronization.
As an example, consider a bank account that is
 shared by multiple customers. Each of these
 customers can make deposits to or withdrawals
 form this account. Your application might have
 a separate thread to process the actions of
 each user.
 The solution to this problem is to synchronize the
  access to this common data.
 This can be done in two ways. First, a method can be
  synchronized by using the synchronized keyword as a
  modifier in the method declaration.
 When a thread begins executing a synchronized
  instance method, it automatically acquires a lock on
  that object.
 The lock is automatically relinquished when the
  method completes.
 Only one thread has this lock at any time.
 Therefore, only one thread may execute any of the
  synchronized instance methods for that same object at
  a particular time.
 If a second thread attempts to execute a synchronized
  instance method for that same object, the JVM
  automatically causes the second thread to wait until
  the first thread relinquishes the lock.
 When a thread begins executing a synchronized static
  method, it automatically acquires a lock on the
  associated Class object.
 Another way to synchronize access to common data is
  via a synchronized statement block. This has the
  following syntax:
  synchronized(obj)
  {
       //statement block
  }
Here, obj is the object to be locked. If you wish to protect
  instance data, you should lock against that object. If
  you wish to protect class data, you should lock the
  appropriate Class object.
                 Dead Lock
Deadlock is an error that can be encountered in
 multithreaded programs.
It occurs when two or more threads wait for
 ever for each other to relinquish locks.
Assume that thread1 holds lock on object1 and
 waits for a lock on object2. thread2 holds a lock
 on object2 and waits for a lock on object1.
 neither of these threads may proceed. Each
 waits forever for the other to relinquish the lock
 it needs.
Deadlock situations can also arise that involve
 more than two threads. Assume that thread1
 waits for a lock held by thread2. thread2 waits
 for a lock held by thread3. thread3 waits for a
 lock held by thread1.
         Thread Communication
 Deadlock can occur if a thread acquires a lock and
  does not relinquish it.
 Now we will see how threads can cooperate with each
  other. A thread can temporarily release a lock so other
  threads can have an opportunity to execute a
  synchronized method or statement block. That lock
  can be acquired again at a later time.
 The class Object defines 3 methods that allow threads
  to communicate with each other. The wait() method
  allows a thread that is executing a synchronized
  method or statement block on that object to release
  the lock and wait for a notification from another thread.
    Void wait() throws InterruptedException
    Void wait(long msec) throws InterruptedException
    Void wait(long msec, int nsec) throws InterruptedException
 The first form causes the current thread to wait
  indefinitely.
 The second form causes the current thread to wait for
  msec.
 The last form causes the current thread to wait for
  msec plus nsec.
 The notify() method allows a thread that is executing a
  synchronized method to notify another thread that is
  waiting for a lock on this object.
 If several threads are waiting, only one of these is
  selected. The selection criteria are determined by the
  implementer of the JVM. The signature of this method
  is shown here:
       void notify();
 The notifyAll() method allows a thread that is
  executing synchronized method to notify all threads
  that are waiting for a lock on this object. The signature
  of this method is shown here:
       void notifyAll();
 It is important to understand that when a thread
  executes the notify() or notifyAll() method, it does not
  relinquish its lock at that moment. This occurs only
  when it leaves the synchronized method.
 The net effect of the notify() and notifyAll() methods is
  that one thread resumes its execution of the
  synchronized method. It returns form the wait()
  method and continues executing the next statement.

				
DOCUMENT INFO
Shared By:
Tags:
Stats:
views:5
posted:8/7/2011
language:English
pages:33
Description: Java set 1