Powered by Blogger.

Tuesday 15 March 2016

Multithreaded Programming in java

1 comment :
Thread: A Thread is a single Sequential flow of control with in a program. In java thread can be implemented in two ways. one is by "implementing" Runnable interfaces and the other way is by "Extending" thread class .
Thread class defines several methods that help manage threads.
Method Meaning
getName Obtain a thread's Name
getPriority Obtain a thread's Priority
isAlive Determine if a thread is still Running
join Wait for a thread to terminate.
run Entry point for the thread.
sleep Suspend a thread for a period of time.
start start a thread by calling its run method.

Implementing Thread Class: The easiest way to create a thread is to create a class that implements the Runnable interface. Runnable abstracts aunit of executable code. you can construct a thread on any object that implements Runnable. to implement Runnable, a calss need only implement a single method called run(), which is declared like this:

you create a class that implements Runnable, you will instantiate an object of type Thread from within that class. Thread defines several constructors. The one that we will use is shown here:

In this constructor, threadObject is an instance of a class that implements the Runnable interface. This defines where execution of the thread will begin. The name of the new thread is specified by threadName.
The new thread is created, it will not start running until you call its start() method, which is declared within Thread. in essence, start() executes a class to runn(). The start() method is shown here:

Example:



Extending Thread: The second way to create a thread is to create a new class that extends Thread, and then to create an interface of that class. the extending class must override the run() method, which is the entry point for the new thread. it must also call start() to begin execution of the new thread. here is the preceding program rewritten to extend Thread:


This program generates the same output as the preceding version. As you can see, the child thread is created by instantiating an object of NewThread, which is derived from Thread.
Notice the call to Super() inside NewThread. This invokes the following from of the Thread constructor:
public Thread(String threadName)
Here, threadNmae Specifies the name of the thread.
Using isAlive() and join():
Sometimes one thread needs to know when another thread is ending. In java, isAlive() and join() are two different methods to check whether a thread has finished its execution.
The isAlive() methods return true if the thread upon which it is called is still running otherwise it return false.
But, join() method is used more commonly than isAlive(). This method waits until the thread on which it is called terminates.
Using join() method, we tell our thread to wait until the specifid thread completes its execution. There are overloaded versions of join() method, which allows us to specify time for which you want to wait for the specified thread to terminate.
Example:


Thread Priorities:Thread priorities are used by the thread scheduler to decide when each thread should be allow to run.
To set a thread's priority, use the setPriority() method, which is a member of Thread.
final void setPriority(int level)
Here, level specifies the new priority setting for the calling thread. the value of level must be within the range MIN_PRIORITY and MAX_PRIORITY. Currently, these values are 1 and 10, respectively. To returns a thread to default priority, specify NORM_PRIORITY, which is currently 5. These priorities are defined as static final variables within Thread. you can obtain the current priority setting by calling the getPriority() method of Thread, shown here: final int getPriority().

Synchronization: Synchronization is the process of allowing threads to execute one after another. Synchronization control the access the multiple treads to a shared resources without synchronization of threads, one thread can modify a shared variable while another thread can update the same shared variable, which leads to significant error.
Using Synchronization Methods: It is easy in java, because all objects have their own implicit monitor associated with them. To enter on object's monitor, just call a method that has been modified with the synchronized keyword. while a thread is inside a synchronized method, all other threads that try to call it on the same instance have to wait. To exit the monitor and relinquish control of the object to the next waiting thread, the owner of the monitor simply returns form the synchronization method.
Example:


Interthread Communication

No comments :
Java includes an elegant Interprocess communication mechanism via the wait(), notify() and notifyAll() methods.These methods are implemented as final method in object, so all classes have them. all three methods can be called only from within a synchronized context. Although conceptually advanced from a computer science perspective, the rules for using these methods are actually quite simple:
wait(): Tells the calling thread to given up the monitor and go to sleep until some other thread enters the same monitor and calls notify() or notifyAll().
notify(): wakes up a thread that called wait() on the same object.
notifyAll(): wakes up a thread that called wait() on the same object. One of the threads will be granted access.

These methods are declared within Object, as shown here:

The proper way to write this program in java is to use wait() and notify() to signal in both directions, shown here:

Output:

Deadlock

No comments :
A Special type of error that you need to avoid that relates specifically to multitasking is Deadlock, which occurs when two threads have a circular dependency on a pair of synchronization objects.
Deadlock is a difficult error to debug for two reasons.
  • In general, It occurs only rarely, when the two threads time-slice in just the right way.
  • It may involve more than two threads and two synchronization object.
Example: A example of Deadlock.

Output:

Obtaining A Thread's State

No comments :
A Thread can exist in a number of different states. you can obtain the current state of a thread by calling the getState() method defined by Thread. It is shown here:

It returns a value of type Thread.State that indicates the state of the thread at the time at which the call was made. State is an enumeration defined by Thread.
Here are the values the can be returned by getState().

Value State
BLOCKED A Thread that has suspended execution because it is waiting to acquire a look.
NEW A Thread that has not begun execution.
RUNNABLE A Thread that either is currently executing or will execute when it gains access to the CPU.
TERMINATED A Thread that has completed execution.
TIMED_WAITING A Thread that hsa suspended execution for a specified period of time, such as when it has called sleep(). This state is also entered when a timeout version of wait() or join() is called.
WAITING A Thread that has suspended execution because it is waiting for some action to occur. for example, it is waiting because of a call to a non-timeout version of wait() or join().

Figure: Diagrams how the various thread states relate.