jump to navigation

Threads in Java July 28, 2005

Posted by Coolguy in J2SE.
  • A thread is a single sequential flow of control within a program
  • There are two ways to create threads
  • Extend the Thread class itself.
  • Implement the Runnable interface

Extending Thread

  • Subclass the Thread class and override the run method
  • The Thread class implements Runnable interface, which defines run() method.
  • To create a thread, Thread class can be extended and the run() method must be overridden.
  • In this method, the code to be executed by the thread is defined.
  • Thread class defines many other methods too, which may or may not be overridden.
  • In general, Thread should be extended to create a new thread only if methods other than run() are to be extended. Otherwise, it is probably better to implement Runnable interface.

Implementing Runnable

  • Provide a class that implements the Runnable interface and therefore implements the run method
  • It is the simplest way to create a new thread.
  • This interface defines only run() method.
  • To implement Runnable, a class need only implement run(), which is declared as public and void in Runnable.
  • After the class that implements Runnable is created, it can be passed in the constructor of Thread to instantiate an object of Thread.

Execution of a thread

  • To execute a thread, the thread is first created and then the start() method is invoked on the thread
  • Eventually the thread would execute and the run method would be invoked.
  • You should note that the run method should not be invoked directly.
  • When the run method ends, the thread is supposed to “die”.

Thread states

  • When you call start() on a thread, the thread does not run immediately.
  • It goes into a ready-to-run state and stays there until the scheduler moves it to the “running state”.
  • Then the run() is called. In the course of executing run(), the thread may temporarily give up the CPU and enter some other state for a while.
  • The thread states are:
  • Ready State : A thread in this state is ready for execution, but is not being currently executed. Once a thread in the ready state gets access to the CPU, it gets converted to running state
  • Running : A thread is said to be in running state when it is being executed. This thread has access to CPU
  • Dead : A thread reaches “dead” state when the run method has finished execution. This thread cannot be executed now
  • Waiting : In this state the thread is waiting for some action to happen. Once that action happens, the thread gets into the ready state. A waiting thread can be in one of the following states – sleeping, suspended, blocked, waiting for monitor.
  • Sleeping : A thread being executed can invoke the sleep() method to cease executing, and free up the CPU. This thread would go to the “sleep” state for the specified amount of time, after which it would move to the “ready” state.
  • Suspended
  • Blocked
  • Starting a Thread : start method
  • Making a Thread Not Runnable : sleep , wait ,blocking on I/O.
  • Stopping a Thread : Stop method has been deprecated.

Java 1.5 thread states are:

  • NEW

The following conditions may prevent a thread from executing:

  • The run () method has completed and returned.
  • An unchecked exception has been thrown from within the run () method and it is unhandled.
  • The JVM has exited due to any reason.
  • A deadlock has occurred.
  • The thread has been stopped from executing by the program itself.


  • When two or more threads need access to a shared resource, they need some way to ensure that the resource will be used only by one thread at a time.
  • The process by which this is ensured is called Synchronization.
  • Key to synchronization is the concept of the monitor (also called Semaphore).
  • A monitor is an object that is used as a mutually exclusive lock, or mutex.
  • Only one thread can own a monitor at a given time.
  • When a thread acquires a lock, it is said to have entered the monitor.
  • All other threads attempting to enter the locked monitor will be suspended until the first thread exits the monitor.
  • A thread that owns a monitor can reenter the same monitor if it so desires.
  • There are two ways to synchronize your code:
  • Using synchronized methods
  • The synchronized statement

Using synchronized methods:

  • Synchronizing is easy in Java because all objects have their own monitor associated with them.
  • To enter an object’s monitor, just call a method that has been modified with the synchronized keyword.
  • While a thread is inside a synchronized method, all other threads that try to call it ( or any other synchronized method) on the same instance have to wait.

The synchronized statement:

  • If you want to synchronize access to objects of a class that was not designed for multi-threaded access i.e. the class does not use synchronized methods or if you do not access to the source code of the class, then simply put calls to the methods defined by this class inside a synchronized block

    synchronized ( object){

    // statements to be synchronized.


    Here object is a reference to the object being synchronized.

Inter-thread communication:

  • Java includes an elegant inter-process communication via wait(), notify() and notifyAll().
  • These methods are implemented as final methods in Object, so all classes have them.
  • All these three methods can be called only from within a synchronized method.
  • The method wait() tells the calling thread to give up the monitor and go to sleep until some other thread enters the monitor and calls notify().
  • Additional forms of wait() exist that allow you to specify a period of time to wait.
  • The method notify() wakes up the first thread that called wait() on the same object.
  • The method notifyAll() wakes up all the threads that called wait() on the same object. The highest priority thread will run first.

Thread priorities:

  • Thread priorities are integers that specify the relative priority of one thread to another.
  • These are used by the thread scheduler to decide when each thread should be allowed to run. (Thread scheduler is a piece of system code . The scheduler might be part of JVM or host operating system. It determines which thread is actually running on each available CPU at a given time.)
  • A thread’s priority is used to decide when to switch from one running thread to the next. This is called a context-switch.
  • The rules that determine when a context switch takes place are:
  • A thread can voluntarily relinquish control. This is done by explicitly yielding, sleeping or blocking on pending I/O. In this scenario, all other threads are examined, and the highest priority thread that is ready to run is given the CPU.
  • A thread can be preempted by a higher priority thread. In this case, a lower priority thread that does not yield the processor is simply preempted – no matter what it is doing – by a higher priority thread. This is called preemptive multithreading.

Controlling threads

  • Yielding
    A call to the yield() method causes the currently executing thread to move to the ready state if the scheduler is willing to run any other thread in its place.
  • Suspending
    Suspending a thread is a mechanism that allows any arbitrary thread to make another thread un-runnable for an indefinite period of time.
  • Sleeping
    A sleeping thread passes time without doing anything and without using the CPU.
  • Blocking
    Many methods that perform input/output have to wait for some occurrence in the outside world before they can proceed; this behavior is known as blocking.A thread can also become blocked if it fails to acquire the lock for a monitor or if it issues a wait() call. Internally, most blocking for I/O, is implemented using wait() and notify().

Thread Pools

  • A thread pool is a managed collection of threads that are available to perform tasks.
  • Thread pools usually provide improved performance when executing large numbers of tasks due to reduced per-task invocation overhead
  • A means of bounding the resources, including threads, consumed when executing a collection of tasks
  • To use thread pools, you instantiate an implementation of the ExecutorService interface and hand it a set of tasks.


  • The java.util.concurrent.* packages define a wide range of concurrency utilities.
  • Task scheduling framework :The Executor framework
  • Locks : java.util.concurrent.locks package provides a high-performance lock implementation with the same memory semantics as synchronization
  • Synchronizers : General purpose synchronization classes, including semaphores, mutexes, barriers, latches, and exchangers, which facilitate coordination between threads
  • Concurrent collections : Contains several concurrent collections, including the Queue and BlockingQueue interfaces, and high-performance, concurrent implementations of Map, List, and Queue.
  • Atomic variables : Classes for atomically manipulating single variables (primitive types or references), providing high-performance atomic arithmetic and compare-and-set methods.
  • Nanosecond-granularity timing : The System.nanoTime method enables access to a nanosecond-granularity time source for making relative time measurements, and methods which accept timeouts

Interface methods:

void checkAccess ()
void destroy ()
Destroys this thread, without any cleanup. Any monitors it has locked remain locked. (This method is not implemented.)

String getName ()
void setName (String name)
int getPriority ()
void setPriority (int priority)
ThreadGroup getThreadGroup ()
void interrupt ()
boolean isAlive ()
boolean isDaemon ()
boolean isInterrupted ()
Tests whether this thread has been interrupted. The interrupted status of the thread is unaffected by this method.

void join ()
void join (long millis)
Waits at most millis milliseconds for this thread to die. A timeout of 0 means to wait forever. Throws InterruptedException if another thread has interrupted the current thread. The interrupted of the current thread is cleared when this exception is thrown.
void join (long millis, int ns)

void run ()
If this thread was constructed using a separate Runnable object, then that Runnable object’s run method is called; otherwise, this method does nothing and returns.

void setDaemon (boolean on)
Marks this thread as either a daemon or a user thread. The JVM exits when the only threads running are all daemon threads. This method must be called before the thread is started.

void start ()
Causes this thread to begin execution; the JVM calls the run method of this thread. The result is that two threads are running concurrently: the current thread (which returns from the call to the start () method) and the other thread (which executes its run () method). Throws IllegalThreadStateException if the thread was already started.

void resume () Deprecated
void stop () Deprecated
void suspend () Deprecated



No comments yet — be the first.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: