Monday, June 3, 2013

Thread Class Methods Use Example



Example:

The following ThreadClassDemo program demonstrates some of these methods of the Thread class:

// File Name : DisplayMessage.java
// Create a thread to implement Runnable
public class DisplayMessage implements Runnable
{
   private String message;
   public DisplayMessage(String message)
   {
      this.message = message;
   }
   public void run()
   {
      while(true)
      {
         System.out.println(message);
      }
   }
}

// File Name : GuessANumber.java
// Create a thread to extentd Thread
public class GuessANumber extends Thread
{
   private int number;
   public GuessANumber(int number)
   {
      this.number = number;
   }
   public void run()
   {
      int counter = 0;
      int guess = 0;
      do
      {
          guess = (int) (Math.random() * 100 + 1);
          System.out.println(this.getName()
                       + " guesses " + guess);
          counter++;
      }while(guess != number);
      System.out.println("** Correct! " + this.getName()
                       + " in " + counter + " guesses.**");
   }
}

// File Name : ThreadClassDemo.java
public class ThreadClassDemo
{
   public static void main(String [] args)
   {
      Runnable hello = new DisplayMessage("Hello");
      Thread thread1 = new Thread(hello);
      thread1.setDaemon(true);
      thread1.setName("hello");
      System.out.println("Starting hello thread...");
      thread1.start();
     
      Runnable bye = new DisplayMessage("Goodbye");
      Thread thread2 = new Thread(hello);
      thread2.setPriority(Thread.MIN_PRIORITY);
      thread2.setDaemon(true);
      System.out.println("Starting goodbye thread...");
      thread2.start();

      System.out.println("Starting thread3...");
      Thread thread3 = new GuessANumber(27);
      thread3.start();
      try
      {
         thread3.join();
      }catch(InterruptedException e)
      {
         System.out.println("Thread interrupted.");
      }
      System.out.println("Starting thread4...");
      Thread thread4 = new GuessANumber(75);
                  thread4.start();
      System.out.println("main() is ending...");
   }
}


This would produce following result. You can try this example again and again and you would get different result every time.


Starting hello thread...
Starting goodbye thread...
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Thread-2 guesses 27
Hello
** Correct! Thread-2 in 102 guesses.**
Hello
Starting thread4...
Hello
Hello
..........remaining result produced.

Thread Class Methods With Description



Thread Methods:

 

Following is the list of important methods available in the Thread class.

SN
Methods with Description
1
public void start()

Starts the thread in a separate path of execution, then invokes the run() method on this Thread object.
2
public void run()

If this Thread object was instantiated using a separate Runnable target, the run() method is invoked on that Runnable object.
3
public final void setName(String name)

Changes the name of the Thread object. There is also a getName() method for retrieving the name.
4
public final void setPriority(int priority)

Sets the priority of this Thread object. The possible values are between 1 and 10.
5
public final void setDaemon(boolean on)

A parameter of true denotes this Thread as a daemon thread.
6
public final void join(long millisec)

The current thread invokes this method on a second thread, causing the current thread to block until the second thread terminates or the specified number of milliseconds passes.
7
public void interrupt()

Interrupts this thread, causing it to continue execution if it was blocked for any reason.
8
public final boolean isAlive()

Returns true if the thread is alive, which is any time after the thread has been started but before it runs to completion.

The previous methods are invoked on a particular Thread object. The following methods in the Thread class are static. Invoking one of the static methods performs the operation on the currently running thread

 
SN
Methods with Description
1
public static void yield()

Causes the currently running thread to yield to any other threads of the same priority that are waiting to be scheduled
2
public static void sleep(long millisec)

Causes the currently running thread to block for at least the specified number of milliseconds
3
public static boolean holdsLock(Object x)

Returns true if the current thread holds the lock on the given Object.
4
public static Thread currentThread()

Returns a reference to the currently running thread, which is the thread that invokes this method.
5
public static void dumpStack()

Prints the stack trace for the currently running thread, which is useful when debugging a multithreaded application.

Creating Thread By Extending Thread Class



Create Thread by Extending Thread:

The second way to create a thread is to create a new class that extends Thread, and then to create an instance 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.

 

Example:

Here is the preceding program rewritten to extend Thread:

// Create a second thread by extending Thread
class NewThread extends Thread {
   NewThread() {
      // Create a new, second thread
      super("Demo Thread");
      System.out.println("Child thread: " + this);
      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 ExtendThread {
   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.