Wednesday, 6 August 2014

Thread In Java or Basics of Thread or Runnable vs Thread

Multitasking allows several activities to occur concurrently on the computer. A distinction is usually made between:
  • Process-based multitasking
  • Thread-based multitasking 
Process-based multitasking, which allows processes (i.e., programs) to run concurrently on the computer. A familiar example is running the spreadsheet program while also working with the word-processor. 

Thread-based multitasking, which allows parts of the same program to run concurrently on the computer. A familiar example is a word-processor that is printing and formatting text at the same time. This is only feasible if the two tasks are performed by two independent paths of execution at runtime. The two tasks would correspond to executing parts of the program concurrently. The sequence of code executed for each task defines a separate path of execution, and is called a thread (of execution).

In a single-threaded environment only one task at a time can be performed. CPU cycles are wasted, for example, when waiting for user input. Multitasking allows idle CPU time to be put to good use.

Thread-based multitasking as compared to process-based multitasking are threads share the same address space context switching between threads is usually less expensive than between processes cost of communication between threads is relatively low. 

Java supports thread-based multitasking and provides high-level facilities for multithreaded programming. Thread safety is the term used to describe the design of classes that ensure that the state of their objects is always consistent, even when the objects are used concurrently by multiple threads.

Overview of Threads

A thread is an independent sequential path of execution within a program. e.g. It maintained in separate stack at runtime by JVM. Many threads can run concurrently within a program. At runtime, threads in a program exist in a common memory space and can, therefore, share both data and code, that is, they are lightweight compared to processes. They also share the process running the program.Every thread in Java is created and controlled by a unique object of the java.lang.Thread class. 

The Main Thread

When a application run, a user thread is automatically created to execute the main() method. This thread is called the main thread. If no other user threads are spawned, the program terminates when the main() method finishes executing. All other threads, called child threads, are spawned from the main thread, inheriting its user-thread status. The main() method can then finish, but the program will keep running until all the user threads have finished. Calling the setDaemon(boolean) method in the Thread class marks the status of the thread as either daemon or user, but this must be done before the thread is started. Any attempt to change the status after the thread has been started, throws an IllegalThreadStateException. Marking all spawned threads as daemon threads ensures that the application terminates when the main thread dies.

Thread Creation

A thread in Java is represented by an object of the Thread class. Implementing threads is achieved in one of two ways:
  • By implementing the java.lang.Runnable interface
  • By extending the java.lang.Thread class
Implementing the Runnable Interface

The Runnable interface has the following specification, comprising one method prototype declaration:

                     public interface Runnable { void run(); }

A thread, which is created based on an object that should implement the Runnable interface, and should override it's public method run(). The run() method defines an independent path of execution and thereby the entry and the exits for the thread. The thread ends when the run() method ends, either by normal completion or by throwing an uncaught exception.
An object of this class is a Runnable object.An object of Thread class is created by passing a Runnable object as argument to the Thread constructor. The Thread object now has a Runnable object that implements the run() method.
The start() method is invoked on the Thread object to start the thread. The start() method returns immediately after a thread has been spawned.
The run() method of the Runnable object is eventually executed by the thread represented by the Thread object on which the start() method was invoked.




Example is given below-

public class CreateThreadRunnableExample implements Runnable{

       public void run(){
             
                for(int i=0; i < 5; i++){
                        System.out.println("Child Thread : " + i);
                     
                        try{
                                Thread.sleep(50);
                        }
                        catch(InterruptedException ie){
                                System.out.println("Child thread interrupted! " + ie);
                        }
                }
             
                System.out.println("Child thread finished!");
        }
     
        public static void main(String[] args) {
                Thread t = new Thread(new CreateThreadRunnableExample(), "My Thread");         
                t.start();
             
                for(int i=0; i < 5; i++){
                     
                        System.out.println("Main thread : " + i);
                     
                        try{
                                Thread.sleep(100);
                        }
                        catch(InterruptedException ie){
                                System.out.println("Child thread interrupted! " + ie);
                        }
                }
                System.out.println("Main thread finished!");
        }
}

output of this thread example would be

Main thread : 0
Child Thread : 0
Child Thread : 1
Main thread : 1
Main thread : 2
Child Thread : 2
Child Thread : 3
Main thread : 3
Main thread : 4
Child Thread : 4
Child thread finished!
Main thread finished!
Extending Thread Class-

A class can also extend the Thread class directly to create a thread.A class extending the Thread class overrides the run() method from the Thread class to define the code executed by the thread.This subclass may call a Thread constructor explicitly in its constructors to initialize the thread, using the super() call.The start() method inherited from the Thread class is invoked on the object of the class to make the thread eligible for running.

 
The Thread class implements the Runnable interface, which means that this approach is not much different from implementing the Runnable interface directly. The only difference is that the roles of the Runnable object and the Thread object are combined in a single object.
When creating threads, there are two reasons why implementing the Runnable interface may be preferable to extending the Thread class:
  • Extending the Thread class means that the subclass cannot extend any other class, whereas a class implementing the Runnable interface has this option.
  • A class might only be interested in being runnable, and therefore, inheriting the full overhead of the Thread class would be excessive.
public class CreateThreadExample extends Thread{
         public void run(){
             
                for(int i=0; i < 5; i++){
                        System.out.println("Child Thread : " + i);
                     
                        try{
                                Thread.sleep(50);
                        }
                        catch(InterruptedException ie){
                                System.out.println("Child thread interrupted! " + ie);
                        }
                }
             
                System.out.println("Child thread finished!");
        }
     
        public static void main(String[] args) {
              
                CreateThreadExample t = new CreateThreadExample();
                 t.start();
             
                for(int i=0; i < 5; i++){
                     
                        System.out.println("Main thread : " + i);
                     
                        try{
                                Thread.sleep(100);
                        }
                        catch(InterruptedException ie){
                                System.out.println("Child thread interrupted! " + ie);
                        }
                }
                System.out.println("Main thread finished!");
        }
}

 

Inner classes are useful for implementing threads that do simple tasks. The anonymous class below will create a thread and start it:

           ( new Thread() { public void run() { 
                  for(;       ;      ) 
                  System.out.println("Stop the world!");
                  }

             } ).start();

Thread States Or lifecycle
Threads can exist in different states. Just because a thread's start() method has been called, it does not mean that the thread has access to the CPU and can start executing straight away. Several factors determine how it will proceed.

See below diagram-

New: A new thread begins its life cycle in the new state. It remains in this state 
until the program starts the thread. It is also referred to as a born thread.
Runnable: After a newly born thread is started, the thread becomes runnable. 
A thread in this state is considered to be executing its task.
Waiting: Sometimes, a thread transitions to the waiting state while the thread waits
for another thread to perform a task.A thread transitions back to the runnable 
state only when another thread signals the waiting thread to continue executing.
Timed waiting: A runnable thread can enter the timed waiting state for a specified 
interval of time. A thread in this state transitions back to the runnable state when 
that time interval expires or when the event it is waiting for occurs.
Terminated: A runnable thread enters the terminated state when it completes its 
task or otherwise terminates.

Thread methods

final boolean isAlive()
This method can be used to find out if a thread is alive or dead. A thread is alive if
it has been started but not yet terminated, that is, it is not in the Dead state.

final int getPriority() 
final void setPriority(int newPriority)
The first method returns the priority of the current thread. The second method 
changes its priority. The priority set will be the minimum of the two values: the 
specified newPriority and the maximum priority permitted for this thread.

static void yield()
This method causes the current thread to temporarily pause its execution and, 
thereby, allow other threads to execute.

static void sleep (long millisec) throws InterruptedException
The current thread sleeps for the specified time before it takes its turn at running 
again.

final void join() throws InterruptedException 
final void join(long millisec) throws InterruptedException
A call to any of these two methods invoked on a thread will wait and not return 
until either the thread has completed or it is timed out after the specified time, 
respectively.

void interrupt()
The method interrupts the thread on which it is invoked. 
In the Waiting-for-notification, Sleeping, or Blocked-for-join-completion states, 
the thread will receive an InterruptedException.

static Thread currentThread()-   This method returns a reference to the Thread 
object of the currently executing thread.

final String getName() -returns the name of the thread

final void setName(String name)- sets the thread's name to the argument.

void run() -The Thread class implements the Runnable interface by providing an 
implementation of the run() method. This implementation does nothing. Subclasses
of the Thread class should override this method.If the current thread is created 
using a separate Runnable object, then the Runnable object's run() method is called.

final void setDaemon(boolean flag)-sets the status of the thread either as a daemon 
thread or as a user thread, depending on whether the argument is true or false, 
respectively. The status should be set before the thread is started.

final boolean isDaemon()-method returns true if the thread is a daemon thread, 
otherwise, false.

void start()- This method spawns a new thread, that is, the new thread will begin 
execution as a child thread of the current thread. The spawning is done 
asynchronously as the call to this method returns immediately. It throws an 
IllegalThreadStateException if the thread was already started.


That it about thread basics!!!!

If you want learn advance Threading concept click here 
We will discus a lot of new things about threading -

Like -

Joining
Deadlock
Synchronizing
Locking
wait and notify
Thread priority
Thread sheduler

No comments:

Post a Comment