Monday, June 3, 2013

Creating Thread By Implementing Runnable Interface



Create Thread by Implementing Runnable:

The easiest way to create a thread is to create a class that implements the Runnable interface.
To implement Runnable, a class need only implement a single method called run ( ), which is declared like this:

public void run( )

You will define the code that constitutes the new thread inside run () method. It is important to understand that run () can call other methods, use other classes, and declare variables, just like the main thread can.
After 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:

Thread(Runnable threadOb, String threadName);

Here, threadOb is an instance of a class that implements the Runnable interface and the name of the new thread is specified by threadName.
After the new thread is created, it will not start running until you call its start( ) method, which is declared within Thread. The start ( ) method is shown here:

void start( );

 

 

Example:


Here is an example that creates a new thread and starts it running:
// Create a new thread.
class NewThread implements Runnable {
   Thread t;
   NewThread() {
      // Create a new, second thread
      t = new Thread(this, "Demo Thread");
      System.out.println("Child thread: " + t);
      t.start(); // Start the thread
   }
// This is the entry point for the second thread.
public void run() {
      try {
         for(int i = 5; i > 0; i--) {
            System.out.println("Child Thread: " + i);
            // Let the thread sleep for a while.
            Thread.sleep(500);
         }
     } catch (InterruptedException e) {
         System.out.println("Child interrupted.");
     }
     System.out.println("Exiting child thread.");
   }
}
class ThreadDemo {
   public static void main(String args[]) {
      new NewThread(); // create a new thread
      try {
         for(int i = 5; i > 0; i--) {
           System.out.println("Main Thread: " + i);
           Thread.sleep(1000);
         }
      } catch (InterruptedException e) {
         System.out.println("Main thread interrupted.");
      }
      System.out.println("Main thread exiting.");
   }
}

This would produce following result:

Child thread: Thread[Demo Thread,5,main]
Main Thread: 5
Child Thread: 5
Child Thread: 4
Main Thread: 4
Child Thread: 3
Child Thread: 2
Main Thread: 3
Child Thread: 1
Exiting child thread.
Main Thread: 2
Main Thread: 1
Main thread exiting.

Creating Threads In java



Creating a Thread:

Java defines two ways in which this can be accomplished:


·         You can implement the Runnable interface.

·         You can extend the Thread class, itself.

For Both ways examples ....please Read :

1. Thread By Extending.

2. Thread By Implementing.

Multi-Threading In Java with Multi-Tasking



Multithreading:

·         THREAD: A flow of control is known as THREAD.

MULTITHREADED PROGRAM:-

·         If a program is containing multiple flows of controls, then that program is known as Multi-threaded program.
OR
·         A Program is said to be a Multithreaded program in which there exists n number of subprograms, for each such subprograms, there exists  a separate flow of control (thread) and all such flow of controls are executing concurrently such flow of controls are known as “threads” and such type of applications are known as “MULTITHREADED APPLICATIONS”.
·         The languages like C/C++ are treated as Single Threaded Modeling Language (STML), since there exist single flow of control. In STML, the program will be executing in Sequential manner.
·         The languages like Java and .NET are treated as MULTITHREADED MODELLING LANGUAGE (MTML), since there is a possibility to exist multiple flows of controls. In MTML, we can achieve concurrent execution. Hence, Java and .NET languages are suitable for developing Internet application (Distributed application).
·         Whenever we write a Java program, by default there exist, 2 types of threads. They are:
(1)    Background Thread or Main Thread or Parent Thread.
(2)    Foreground Thread or Sub Thread or Child Thread.
·         A Background Thread is one which always monitors the status of Foreground Threads.
·         Every Java program contains single background thread.
·         A Foreground Thread is one which always executes user’s specific sub-programs.
·         In a Java program we create n number of Foreground Thread.
·         Java program is by default Multithreaded, since there exists two Threads one  Thread is executing our java program and other is Thread is monitoring (Garbage Collector) to that thread which is executing java Program.
·         C/C++ does not contain multithreading as a predefined facilities where as Java contains.
·         In java, libraries are known as API (Application Programming Interface).

MULTITASKING:

·         In this, all the jobs or tasks get executed in different memory areas. In this case, in the complete program all the tasks will not be waiting for the execution in a queue, they will execute simultaneously/concurrently means CPU doesn’t take much more time. But it will be expensive when there are number of users and number of jobs.




MULTITHREADING
·         In term of Multithreading, we call all the tasks as Threads only.

 

Multithreading

·      

          Java provides built-in support for multithreaded programming. A multithreaded program contains two or more parts that can run concurrently. Each part of such a program is called a thread, and each thread defines a separate path of execution.
·         A multithreading is a specialized form of multitasking. Multitasking threads require less overhead than multitasking processes.
·         Process: A process consists of the memory space allocated by the operating system that can contain one or more threads. A thread cannot exist on its’ own; it must be a part of a process. A process remains running until all of the non-daemon threads are done executing.
·         Multithreading enables you to write very efficient programs that make maximum use of the CPU, because idle time can be kept to a minimum.

Life Cycle of a Thread:

A thread goes through various stages in its life cycle. For example, a thread is born, started, runs, and then dies. Following diagram shows complete life cycle of a thread.




Above mentioned stages are explained here:
  • 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 transition 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 Priorities:

Every Java thread has a priority that helps the operating system determine the order in which threads are scheduled.

Java priorities are in the range between MIN_PRIORITY (a constant of 1) and MAX_PRIORITY (a constant of 10). By default, every thread is given priority NORM_PRIORITY (a constant of 5).
Threads with higher priority are more important to a program and should be allocated processor time before lower-priority threads. However, thread priorities cannot guarantee the order in which threads execute and very much platform dependent.