Search this Site


More books @amazon.com

Home- Tutorial on Threads

What is a thread:
A thread is a single sequential flow of control within a program. Threads in Java is defined by a class in the standard Java library.

Creating Threads:
 In order to create a thread , you will start by creating a Thread object as shown below

Thread myThread = new Thread()

Thread does not run simply because you have created a Thread object, it needs to be configured. This would entail setting the initial priority of the thread, its name etc.  The standard implementation of Thread class has a run() method. This method does nothing and needs to be overridden to get any work done from the thread. You run the thread by calling its start() method which will invoke the threads run() method, making the thread active. 

Following example shows how to create a thread, by extending Thread class

public class MyClass extends Thread 

  public void run()  //
run() method is overridden
 { 
    System.out.println ("Welcome to my website");
  }

  public static void main (String arguments[]) 
 {
     new MyClass().start(); //
start() method is invoked
  } 
}

Yet another way of creating thread is to implement  Runnable interface and pass it as an argument to the thread's constructor

public class MyClass implements Runnable
{
  public void run()
  {
    System.out.println ("Welcome to my website");
  }

  public static void main (String args [])
  {
     Thread t1 = new Thread (new MyClass());
     t1.start();
  }
}

Threads Lifecycle:
A thread can be in one of the five states during its entire lifecycle. These states are new, ready, running, inactive and dead. When a thread is created it is in new state. The only method which can be used on such thread is start(). When start() method is called, the thread do not start running immediately. It goes in ready state. A ready thread is "runnable", which means it can run. However a runnable thread might not be in the running state immediately because the CPU might be occupied with some other process and it has to allocate resources for this thread to run. When thread begins to execute, it is in the running state .A thread runs until it becomes inactive by call to sleep() or wait() methods. When a thread complete the execution of its run() method or is killed explicitely, it becomes dead.

Thread Priority:
In order to co-ordinate activities of more than one thread , Java uses fixed
priority scheduling logic. A new thread takes it's priority from the thread
that created it but you can explicitly set the priority of thread either higher or lower , as long as it ranges between MIN_PRIORITY and MAX_PRIORITY values that are defined in Thread class. The default priority is in between this two values and is defined to be NORM_PRIORITY. The highest priority thread is always the one that is running. Java has the ability to switch between two threads  with the same priority. A thread can also yield to other threads that have the same priority as itself or to new threads which have been escalated from a lower priority thread to a high priority thread. You could set the thread priority by adding following statement

myThreadObj.setPriority(Thread.MAX_PRIORITY)
myThreadObj.setPriority(Thread.MIN_PRIORITY)

Synchronization:
In a multithreaded environment, any method that accesses data updated in two or more threads should be declared as synchronized, as shown below

synchronized void updateMethod() {....

If one thread invokes a synchronized method on an object, that object is locked and another thread invoking synchronized method on that same object will be blocked until the lock is released. Thus synchronization provides exclusive access to the object.

Monitors/Locks:
Java associates a monitor (also called lock) with each object and with each class. When a thread enters a synchronized method, that thread also enters the monitor  and when thread exits the synchronized method, it also comes out of the monitor. There are two types of monitors, first is instance monitor and second is static monitor. Java uses monitor associated with the instance when instance methods are synchronized and uses class monitor when static methods are synchronized.

Deadlocks:
Synchronization is not always the cure for all ills. Deadlock occurs when thread "A"  holds lock "1" and needs lock "2", while thread "B" holds lock "2" and needs lock "1" to become free, as a result the system goes into a "deadly embrace". Java provides methods that would help threads work in harmony. Following are the signatures of these methods. 

public final void wait() throws InterruptedException {...
public final void wait( long timeout) 
    throws InterruptedException {...
public final void notify() 
public final void notifyAll() 

These methods are defined in class Object and can be called only within synchronized methods. 

Yielding to other threads:
A thread at any time can give up its' right to execute by calling the
yield() method of the Thread class.  This method is defined  as
public static void yield(). When this method is called the current execution of this thread will pause for a moment and allow the other thread to run. The so called "other" thread must have the same priority as the yielding thread .Any attempts to yield to a low priority threads are ignored. This is similar to a athlete who passes the baton to the next runner in his team, in a relay race. The athlete can pass the baton only to the runner in his team (consider it as a thread of same priority) , not to the runner in any other team (low priority threads).

Stopping a thread:
Two methods in Thread class, sleep() and interrupt() needs a special mention. sleep() causes the currently executing thread to momentarily cease execution for the specified number of milliseconds. The thread does not lose ownership of any locks it may have acquired. A thread can signal another thread that it should stop executing by calling the interrupt() method. This in itself does not necessarily stop the thread. It just sets a flag in the thread that needs to be checked in the run() method.

Volatile:
This keyword may be applied to the data. This informs the compiler that several threads may be accessing this simultaneously. The data should therefore be completely refreshed from memory and completely stored back after each access.

Self Evaluation Questions:
Take the Quiz

More Resources:

Books:
Java Threads (Java Series (O'Reilly & Associates))

Mastering Java Threads Two-Day Course

 

[ TOP OF PAGE ]

MAIN MENU

BEFORE YOU BEGIN

Certification FAQ
Certification Objectives

TICKLE YOUR GRAY CELLS

Interactive Sample Java Test
Over 6000 students have  tested !

Object Equivalence 

Threads

SCJP STUDY TOOLS

Study Tips

Certification Books

Other Certification Sites

Tutorials

SCJP Revision Tips

MISCELLANEOUS LINKS

Java Magazines

Java IDE's

Career Related Websites


The Complete Idiot's Guide to Java 2

 

 

 

Disclaimer     © 2000-01 Sandeep Nachane Feedback