May 12, 2007

MultiThreading Programming In Java.

Filed under: Java — khangharoth @ 9:57 am

Let’s first understand Concurrency :Concurrency is a property of Systems in which several computational process are executing at the same time and potentially interacting with each other.

Concurrency may be physical ,if each unit is executed on a dedicated processor.Its also called true concurrency. If your system has only one CPU ,than it can’t perform true concurrency.Now we have multiple CPU’s in mainstream systems,and these systems are capable of Parallelism or true concurrency.

Concurrency can be logical,If you have single processor system than this is what your system does.Concurrency is just a illusion created by CPU.CPU can execute only one of the programs at a time. The OS maintains the illusion of concurrency by rapidly switching between running programs at a fixed interval, called a time slice. The time slice has to be small enough that the user doesn’t notice any degradation in the usability and performance of the running programs, and it has to be large enough that each program has a sufficient amount of CPU time in which to get useful work done.

So with these basics now let’s move towards more concrete.

Processes (Program) & Threads

  • Process: Is a self contained running program with its own address space.Typically two process share very minimal data,not more than filename etc.Or we can say sharing of data variable is not their.Typical processes on your system are Window Media Player,Outlook,Eclipse etc.These are processes which have their separate memory area and sharing is minimal between them.
  • Operating System is capable of switching the CPU from one process to another ,giving a feel that Media Player and eclipse are running simultaneously.If you are still not clear that perhaps TV analogy will help.In TV ,static images are refreshed on screen so fast that to human mind it appears continuous.
  • Thread or we can say Light-Weight process are concurrent Units which share a single address space.So sharing of data is very common and high.

I think now the difference between a Thread and a Process is clear.Just to make it more clearer:

  • Threads are lightweight compared to processes.
  • Code and Data sharing is easily done in threads as they share same address space.
  • To put in proper perspective , A process can be single threaded or multi threaded.

Its the O.S which switches between various processes and various threads in a single process.Their are different models to achieve this

  • Preemptive multitasking. In preemptive multitasking, the operating system decides how to allocate CPU time slices to each program. At the end of a time slice, the currently active program is forced to yield control to the operating system, whether it wants to or not. Examples of operating systems that support preemptive multitasking are Unix, Windows 95/98, Windows NT and Mac OS X.
  • Cooperative multitasking. In cooperative multitasking, each program controls how much CPU time it needs. This means that a program must cooperate in yielding control to other programs, or else it will hog the CPU. Examples of operating systems that support cooperative multitasking are Windows 3.1 and Mac OS 8.5

Modern O.S generally use preemptive model so your running thread can loose control at any point of time even in some simple assignment statements which seems atomic.Its a very important concept to be learned that a thread can loose control at any stage and will start from that point when again its turn will come.Their are some guaranteed atomic operations in java .

We want to start a new thread when we have a piece of code which can run independently .If done correctly it results in better user experience and also increased performance. To better understand need of multi threading in normal programming lets take an very common example.

Example:Suppose we have a Swing Gui and its displaying a list of Employee’s name and in front of each name their is a button “Get Details”.On click of a specific button ,application picks the corresponding name and retrieves all data related to that employee for display. On Click of button ,action perform method will be called and from this we can make a database call ,gets all the data and than populate the Gui.The catch here is ,action perform method is called by Swing Event Thread.And if we make database call from this thread itself ,till the time our work is complete ,it won’t be able to perform its other responsibility like painting/repainting and firing events.Now if the application task takes too much time (500ms) ,the Gui would appear hang and unresponsive.

This is the perfect place to do Application work in separate thread and free the Event thread as early as possible.So the flow should be: Event Thread(Gives the trigger :Name) —-initiates and returns–>Worker Thread (gets the data related to name ) —hand over data to Event thread–>Swing Thread(updates the Gui).

So Swing thread is free to perform its own responsibilities in the mean time a Time-Consuming task is been performed.I suppose now its clear why multi threading capabilities are needed in modern applications.Sometimes designing a complex problem is easier in concurrent threads rather than in a single flow,like user events with some other task also running.

Now its time to take some real Java examples.In java their are two ways to start a thread.

  • Create a Class which extends Thread Class :Than you put you application code in overridden run method.Basically anything we want to do from this thread is put in run method.Try out example in SimpleThread.txt.Here its important to note that order of execution does not depend on which thread was started first,try for 10-15 times you will notice that sometimes its the second thread which started first although we have done in other way round.So its important to note that we cannot guarantee about the order of execution and also the behavior can be different on different O.S.
  • Create a Class which implements Runnable Interface : In this case also we would put our code in run method.And to start anew thread,we will create a new thread and pass runnable instance to it.Try out example in RunnableExample.txt.Here also order is not guaranteed.

So which is the more preferred way.Well most of the time its the second which is used,because generally our classes are already of some type say Swing Component has so have to extend some other class.In java as multiple inheritance is not allowed so we give thread properties to a class by implementing runnable.

Their is one more handy way to use in application.In our example we just wanted to do some work in a separate thread.To achieve that we can directly use

Thread thread=new Thread(new Runnable(){

public void run() {
* Put your work related code here


Now let’s go through the Life Cycle of a thread for better understanding : A thread can be in one of four states during its lifetime.

  • new – A new thread is one that has been created (using the new operator), but has not yet been started.
  • runnable – A thread becomes runnable once its start() method has been invoked. This means that the code in the run() method can execute whenever the thread receives CPU time from the operating system.
  • blocked – A thread can become blocked if one of the following events occurs:
    • The thread’s sleep() method is invoked. In this case, the thread remains blocked until the specified number of milliseconds elapses.
    • The thread calls the wait() method of an object. In this case, the thread remains blocked until either the object’s notify() method or its notifyAll() method is called from another thread. The calls to wait(), notify() and notifyAll() are typically found within synchronized methods of the object.
    • The thread has blocked on an input/output operation. In this case, the thread remains blocked until the i/o operation has completed.
  • dead – A thread typically dies when the run() method has finished executing.

Also stay away from these methods of Thread Class :stop(), suspend() and resume() .Usesage of these can result of unpredictable results in your program.These methods have been deprecated by Java team.




  1. A online beginner java tutorial website covering basics of programming along with java source code.

    Comment by Beginner Java Tutorial — May 13, 2007 @ 5:37 pm | Reply

  2. jdbc tutorial teaching jdbc programming using java jdbc odbc connectivity on a oracle database with example source codes.

    Comment by JDBC Tutorial — May 13, 2007 @ 5:38 pm | Reply

  3. i’ll go through the material and may include these sites in Java resources.

    Comment by elope — May 14, 2007 @ 4:17 am | Reply

  4. Very interesting article for java beginners

    Comment by Java Beginner — October 30, 2007 @ 5:16 am | Reply

  5. i’m eric. joining a couple boards and looking
    forward to participating. hehe unless i get
    too distracted!


    Comment by xztheericzx — November 5, 2007 @ 11:47 pm | Reply

  6. Hello!
    How are you?

    Comment by mymbomidoulky — November 8, 2007 @ 7:46 pm | Reply

  7. Hey,
    I’m Gerald.

    Just saying hey – I’m new.

    Comment by oOgerryOo — December 16, 2007 @ 9:02 am | Reply

  8. Hi all!
    And What parental control soft do you prefer?

    Comment by Controller — March 21, 2008 @ 1:11 am | Reply

  9. Hello Everybody

    Just wanted to share my new experience.

    If your system fails to start due to an error corresponding to missing HAL.DLL, invalid Boot.ini or any other important system boot files you can fix this by using the XP installation CD. Simply boot from your XP Setup CD and enter the Recovery Console. Then run “attrib -H -R -S” on the C:\Boot.ini file and remove it. Launch “Bootcfg /Rebuild” and then Fixboot


    Comment by admin_papa — August 30, 2008 @ 11:42 pm | Reply

  10. This is quite a up-to-date info. I think I’ll share it on Digg.

    Comment by How to Get Six Pack Fast — April 15, 2009 @ 3:27 pm | Reply

  11. tks for the effort you put in here I appreciate it!

    Comment by MichaellaS — July 20, 2009 @ 3:23 pm | Reply

RSS feed for comments on this post. TrackBack URI

Leave a Reply

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

You are commenting using your 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

Create a free website or blog at

%d bloggers like this: