Thread in Java

Document Sample
Thread in Java Powered By Docstoc
					Thread in Java
    Lang Zhao
• What is Thread?
• Introduction (life circle, Method)
• Thread priority (with example)
• Thread creation (with example)
• Scheduler (with example)
• Synchronization (with example)
• Monitor (with example)
• Daemon (with example)
       What is a thread?
A thread is a lightweight process
which exist within a program and
executed to perform a special task.
Several threads of execution may be
associated with a single process.
In Java programming language
• thread is a sequential path of code
   execution within a program.
• the ‘thread’ class is defined in the
   package java.lang, which needs to
   be imported
Life circle of one thread
          1. New state: the thread is considered
            not alive.
          1. Runnable (Ready-to-run) state:
            A thread start its life. On this state a
            thread is waiting for a turn on the
          3. Running state: the thread is
            currently executing
          4. Dead state: its run() method
          5. Blocked: is waiting the resources that
             are hold by another thread.
Life circle of multiple-threads
  Life circle of multiple-threads
non-runnable states:
Sleeping:      the thread is still alive but it is not runnable. On this state a
  thread sleeps for a specified amount of time. You can use the method
  sleep( ) to stop the running state of a thread.
Waiting      for Notification: A thread waits for notification from another
  thread. The thread sends back to runnable state after sending
  notification from another thread.
Blocked    on I/O: waiting I/O resource, the thread sends back to
  runnable state after availability of resources.
Blocked     for joint completion: waiting the completion of another thread.

Blocked     for lock acquisition: waiting to acquire the lock of an object.
  Some Important Methods
  defined in java.lang.Thread
Method                    Description
start( )        Void      Start the thread by calling its run method

                          This method is the entry point to execute
Run()           void
                          thread, like the main method for application
                          Retrieve the name of the thread object or
getName()       String
                          This method returns the number of active
activeCount()   Int       threads in a particular thread group and all its
                          Returns an object reference to the thread in
currentThread( ) Thread
                          which it is invoked

getPriority()   Int       Returns this thread’s priority

                          This method is used to determine the thread
isAlive()       Boolean
                          is running or not
     Some Important Methods
     defined in java.lang.Thread
Method                     Description
                           Suspends a thread for a specified amount of
sleep( )          void
                           time (in milliseconds)
                           This method interrupt the threads on which it is
interrupt()       void
                           This method and join(long millisec) Throws
                           InterruptedException are invoked on a thread.
join()            void
                           They are not returned until either the thread
                           has completed or it is timed out respectively

                  void     Changes the priority of this thread

                           By invoking this method the current thread
yield( )          void     pause its execution temporarily and allow other
                           threads to execute
                           This method is used to destroy the thread
destroy()         void
                           without any cleanup
         Thread Creation
Two ways:
• Extending the java.lang.Thread Class
• Implementing the java.lang.Runnable
   Prefer for Implementing a
      Runnable Interface
Two reasons:
•   If you extend the Thread Class, that means that subclass
    cannot extend any other Class, but if you implement
    Runnable interface then you can do this.
•   The class implementing the Runnable interface can avoid
    the full overhead of Thread class which can be excessive.
     class MyThread10 implements Runnable{
       Thread t;
       String s=null;
     MyThread10(String s1){
         t=new Thread(this);
       public void run(){
     public class RunableThread{
       public static void main(String args[]){
         MyThread10 m1=new MyThread10("Thread started....");
• Reduces the computation time.
• Improves performance of an application.
• Threads share the same address space so it
  saves the memory.
• Context switching between threads is usually less
  expensive than between processes.
• Cost of communication between threads is
  relatively low.
    Multiple-threads Creation
Implementing a Runnable interface
  class MyThread11 implements Runnable{
    Thread t;
    MyThread11(String s) {
      t=new Thread(this,s);
    public void run() {
      for(int i=0;i<5;i++) {
        System.out.println("Thread Name :"+Thread.currentThread().getName());
        try {
        }catch(Exception e){}
  public class RunnableThread1{
   public static void main(String args[]) {
      System.out.println("Thread Name :"+Thread.currentThread().getName());
      MyThread11 m1=new MyThread11("My Thread 1");
      MyThread11 m2=new MyThread11("My Thread 2");
both threads are registered with the thread scheduler and the CPU
scheduler executes them one by one.
                  Thread Priorities
In Java
1.       The thread scheduler can use the thread priorities to
         determine the execution schedule of threads .
2. The thread scheduler provides the CPU time to thread of highest
priority during ready-to-run state.
3. Priorities are integer values
     –        Thread.MIN_PRIORITY: 1
     –        Thread.MAX_PRIORITY: 10

     –        Thread.NORM_PRIORITY: 5
      Example of set priority
class MyThread12 extends Thread{
  MyThread12(String s){
  public void run(){
    for(int i=0;i<3;i++){
     Thread cur=Thread.currentThread();
     int p=cur.getPriority();
     System.out.println("Thread Name :"+Thread.currentThread().getName());
     System.out.println("Thread Priority :"+cur);
  class MyThread22 extends Thread{
  MyThread22(String s){
public void run(){
    for(int i=0;i<3;i++){
     Thread cur=Thread.currentThread();
     int p=cur.getPriority();
     System.out.println("Thread Name :"+Thread.currentThread().getName());
     System.out.println("Thread Priority :"+cur);
public class ThreadPriority{
  public static void main(String args[]){
    MyThread12 m1=new MyThread12("My Thread 1");
    MyThread22 m2=new MyThread22("My Thread 2");
          Thread Scheduler
• Preemptive scheduling: In Java runtime system, if the
  new thread has a higher priority, the current running thread
  leaves the runnable state and higher priority thread enter to the
  runnable state.

• Time-Sliced (Round-Robin) Scheduling: if two
  threads of the same priority are waiting to be executed by the
  cpu. A running thread is allowed to be execute for the fixed time,
  after completion the time, current thread indicates to the another
  thread to enter it in the runnable state.
•   Only methods (or blocks) can be synchronized, Classes and variable
    cannot be synchronized.

•   All methods in a class need not to be synchronized. A class can have both
    synchronized and non-synchronized methods.

•   If two threads wants to execute a synchronized method in a class, and
    both threads are using the same instance of the class to invoke the
    method then only one thread can execute the method at a time.

•   If a class has both synchronized and non-synchronized methods, multiple
    threads can still access the class's non-synchronized methods. If you have
    methods that don't access the data you're trying to protect, then you don't
    need to synchronize them. Synchronization can cause a hit in some cases
    (or even deadlock if used incorrectly), so you should be careful not to
    overuse it.

•   You can synchronize a block of code rather than a method.

•   Constructors cannot be synchronized
       Synchronized Method of
•   class Share extends Thread{
      static String msg[]={"This", "is", "a", "synchronized", "variable"};
      Share(String threadname){
      public void run(){
      public synchronized void display(String threadN){
        for(int i=0;i<=4;i++)
      }catch(Exception e){}
    public class SynThread1 {
      public static void main(String[] args) {
        Share t1=new Share("Thread One: ");
        Share t2=new Share("Thread Two: ");
• Monitor is any class with synchronized code in it.
• Monitor controls its client threads using wait()
  and notify() ( or notifyAll() ) methods.
• wait() and notify() methods must be called in
  synchronized code.
• Monitor asks client threads to wait if it is
• Normally a call to wait() is placed in while loop.
  The condition of while loop generally tests the
  availability of monitor. After waiting, thread
  resumes execution from the point it left.
                Example of Monitor
public class DemoWait extends Thread{
 int val=20;
 public static void main(String args[]) {
   DemoWait d=new DemoWait();
   new Demo1(d);
 public void run(){
   try {
   System.out.println("value is :"+val);
   }catch(Exception e){}
 public void valchange(int val){
  try {
  synchronized(this) {
  }catch(Exception e){}
class Demo1 extends Thread{
  DemoWait d;
  Demo1(DemoWait d) {
  public void run(){
    System.out.println("Demo1 value is: "+d.val);
  }catch(Exception e){}
In Java,
• any thread can be a Daemon thread.
• Daemon threads are like a service providers for other
  threads or objects running in the same process as the
  daemon thread.
• Daemon threads are used for background supporting tasks
  and are only needed while normal threads are executing.
• If normal threads are not running and remaining threads
  are daemon threads then the interpreter exits.
                       Example of Daemon
public class DaemonThread extends Thread {
      public void run() {
        System.out.println("Entering run method");
             try {
              System.out.println("In run Method: currentThread() is"
                 + Thread.currentThread());
              while (true) {
               try {
               } catch (InterruptedException x) {
                 System.out.println("In run method: woke up again");
             } finally {
               System.out.println("Leaving run Method");
         public static void main(String[] args) {
           System.out.println("Entering main Method");
             DaemonThread t = new DaemonThread();
             try {
             } catch (InterruptedException x) {
             System.out.println("Leaving main method");