Wednesday, 2 April 2014

"Threading Concept on Java"

      What Is a Thread?


All programmers are familiar with writing sequential programs. You've probably written a program that displays "Hello World!", or sorts a list of names, or computes a list of prime numbers. These are sequential programs: each has a beginning, an execution sequence, and an end. At any given time during the runtime of the program there is a single point of execution.A thread is similar to the sequential programs described above: a single thread also has a beginning, an end, a sequence, and at any given time during the runtime of the thread there is a single point of execution. However, a thread itself is not a program. It cannot run on its own, but runs within a program.

Definition: A thread is a single sequential flow of control within a program.

A thread--sometimes known as an execution context or a lightweight process-is a single sequential flow of control within a process.

Thread Example:

The following program is a simple Java application that creates and starts two independent threads:
class TwoThreadsTest {
    public static void main (String[] args) {
        new SimpleThread("Jamaica").start();
        new SimpleThread("Fiji").start();
    }
}
class SimpleThread extends Thread {
    public SimpleThread(String str) {
        super(str);
    }
    public void run() {
        for (int i = 0; i < 10; i++) {
            System.out.println(i + " " + getName());
            try {
                sleep((int)(Math.random() * 1000));
            } catch (InterruptedException e) {}
        }
        System.out.println("DONE! " + getName());
    }
}

Thread  Attributes:

To use threads efficiently and without errors you must understand various aspects of threads and the Java runtime system. You need to know how to provide a body for a thread, the life cycle of a thread, how the runtime system schedules threads, thread groups, and what daemon threads are and how to write them.
                  Java threads are implemented by the Thread class, which is part of the java.lang package. The Thread class implements a system-independent definition of Java threads. But under the hood, the actual implementation of concurrent operation is provided by a system-specific implementation. For most programming needs, the underlying implementation doesn't matter. You can ignore the underlying implementation and program to the thread API described in this lesson and in the other documentation provided with the Java system.

Thread Body:
All of the action takes place in the thread's body--the thread's run method. You can provide the body to a Thread in one of two ways: by subclassing the Thread class and overriding its run method, or by creating a Thread with a Runnable object as its target.
Thread State:
Throughout its life, a Java thread is in one of several states. A thread's state indicates what the Thread is doing and what it is capable of doing at that time of its life: Is it running? Is it sleeping? Is it dead?
Thread Priority:
A thread's priority tells the Java thread scheduler when this thread should run in relation to other threads.
Daemon Threads:
Daemon threads are those that provide a service for other threads in the system. Any Java thread can be a daemon thread.
Thread Group:
All threads belong to a thread group. ThreadGroup, a java.lang class, defines and implements the capabilities of a group of related threads.

Multithreaded Programs:

          The first sample programs in this lesson use either one thread or multiple independent threads that run asynchronously. However, it is often useful to use multiple threads that share data and therefore must run synchronously. Typically, programs that use multiple synchronous threads are called multithreaded programs and require special handling.

Synchronizing Threads:

Often, threads need to share data. For example, suppose you have a thread that writes data to a file while, at the same time, another thread is reading data from that same file. When your threads share information, you need to synchronize the threads to get the desired results. The next section shows you how to synchronize threads in your Java programs.

Fairness, Starvation, and Deadlock

If you write a program in which several concurrent threads are competing for resources, you must take precautions to ensure fairness. A system is fair when each thread gets enough access to limited resource to make reasonable progress. A fair system prevents starvation and deadlock

Starvation occurs when one or more threads in your program is blocked from gaining access to a resource and thus cannot make progress. Deadlock is the ultimate form of starvation; it occurs when two or more threads are waiting on a condition that cannot be satisfied. Deadlock most often occurs when two (or more) threads are each waiting for the other(s) to do something. 

Deadlock and the Dining Philosophers uses the dining philosophers problem to illustrate deadlock. It also discusses ways you can prevent deadlock.

Deadlock and the Dining Philosophers:


The dining philosophers are often used to illustrate various problems that can occur when many synchronized threads are competing for limited resources. 
The story goes like this: Five philosophers are sitting at a round table. In front of each philosopher is a bowl of rice. Between each pair of philosophers is one chopstick. Before an individual philosopher can take a bite of rice he must have two chopsticks--one taken from the left, and one taken from the right. The philosophers must find some way to share chopsticks such that they all get to eat. 
The following applet does a rough animation using an image of Duke for the dining philosophers. This particular algorithm works as follows: Duke always reaches for the chopstick on his right first. If the chopstick is there, Duke takes it and raises his right hand. Next, Duke tries for the left chopstick. If the chopstick is available, Duke picks it up and raises his other hand. Now that Duke has both chopsticks, he takes a bite of rice and says "Mmm!" He then puts both chopsticks down, allowing either of his two neighbors to get the chopsticks. Duke then starts all over again by trying for the right chopstick. Between each attempt to grab a chopstick, each Duke pauses for a random period of time.

The slider controls the amount of time that each philosopher will wait before attempting to pick up a chopstick. When the slider is set to 0, the philosophers don't wait--they just grab--and the applet ends up in deadlock: all the philosophers are frozen with their right hand in the air. Why? Because each philosopher immediately has one chopstick and is waiting on a condition that cannot be satisfied--they are all waiting for the left chopstick, which is held by the philosopher to their left. 
When you move the slider so that the waiting period is longer, the applet may proceed for a while without deadlocking. However, deadlock is always possible with this particular implementation of the dining philosophers problem because it is possible for all five philosophers to be holding their right chopsticks. Rather than rely on luck to prevent deadlock, you must either prevent it or detect it. 
For most Java programmers, the best choice is to prevent deadlock rather than to try and detect it. Deadlock detection is complicated and beyond the scope of this tutorial. The simplest approach to to preventing deadlock is to impose ordering on the condition variables. In the dining philosopher applet, there is no ordering imposed on the condition variables because the philosophers and the chopsticks are arranged in a circle. All chopsticks are equal.
However, we can change the rules in the applet by numbering the chopsticks 1 through 5 and insisting that the philosophers pick up the chopstick with the lower number first. The philosopher who is sitting between chopsticks 1 and 2 and the philosopher who is sitting between chopsticks 1 and 5 must now reach for the same chopstick first (chopstick 1) rather than picking up the one on the right. Whoever gets chopstick 1 first is now free to take another one. Whoever doesn't get chopstick 1 must now wait for the first philosopher to release it. Deadlock is not possible.


0 comments: