bpurcell.org - What is a Java Thread and How does it work?
Calendar
SunMonTueWedThuFriSat
    1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30      

Subject Archives
Amazon EC2 (15)
ColdFusionMX (155)
Corvette (3)
Flash Lite (4)
Flash Media Server (5)
Flash Player (3)
Flex (39)
General Web Dev (14)
HDTV (3)
Jboss (1)
Jquery (2)
JRun (59)
Max 2003 (3)
Other (33)
PC Hardware (16)
Software (17)
SpatialKey (7)
Wireless (8)
Working Out (1)

RSS Feed
Feed Listing

Site Contents
Home
My Blog
ColdFusion
JRun
Flex
Wireless & Networking
Hardware & Gadgets
HDTV
Software Picks
Pictures
Contact Me
Search


My Articles & Papers
Flex Performance
Server/Client
mm.com Under the Hood
Multiple Instances of CFMX
Multiple Instance Config
NLB with ColdFusion
Clustering CFMX for J2EE
Multi-Tier Hardware LB w CFMX
Cisco CSS & Coldfusion MX
JRun 4 Jini based Clustering
WiFi Growth

2ID Tacweb

Other Hobbys
Body-For-Life Challenge

Personal Projects
Family Pool
Deck Gate

username:
password:
 

 
Viewing Individual Entry / Main
August 29, 2003
A java thread is an execution context or a lightweight process. It is a single sequential flow of control within a program. Programmer may use java thread mechanism to execute multiple tasks at the same time.
Thread class and run() Method
  • Basic support for threads is in the java.lang.Thread class. It provides a thread API and all the generic behavior for threads. These behaviors include starting, sleeping, running, yielding, and having a priority.
  • The run() method gives a thread something to do. Its code should implement the thread's running behavior.
    There are two ways of creating a customized thread:
    • Sub classing java.lang.Thread and Overriding run() method.
    • Implementing the java.lang.Runnable Interface.
Thread Scheduling
  • When we say that threads are running concurrently, in practice it may not be so. On a computer with single CPU, threads actually run one at a time giving an illusion of concurrency.
  • The execution of multiple threads on a single CPU based on some algorithm is called thread scheduling.
  • Thread scheduler maintains a pool of all the ready-to-run threads. Based on fixed priority algorithm, it allocates free CPU to one of these threads.
The Life Cycle of a Thread
The following diagram illustrates the various states that a Java thread can be in at any point during its life and which method calls cause a transition to another state.
Thread life cycle
  • Ready-to-run
    A thread starts its life cycle with a call to start(). For example
     MyThread aThread = new MyThread();
     aThread.start();
    
    A call to start() will not immediately start thread's execution but rather will move it to pool of threads waiting for their turn to be picked for execution. The thread scheduler picks one of the ready-to-run threads based on thread priorities.
  • Running
    The thread code is being actively executed by the processor. It runs until it is swapped out, becomes blocked, or voluntarily give up its turn with this static method
     Thread.yield();
    
    Please note that yield() is a static method. Even if it is called on any thread object, it causes the currently executing thread to give up the CPU.
  • Waiting
    A call to java.lang.Object's wait() method causes the current thread object to wait. The thread remains in "Waiting" state until some another thread invokes notify() or the notifyAll() method of this object. The current thread must own this object's monitor for calling the wait().
  • Sleeping
    Java thread may be forced to sleep (suspended) for some predefined time.
     Thread.sleep(milliseconds);
     Thread.sleep(milliseconds, nanoseconds);
    
    Please note that static method sleep() only guarantees that the thread will sleep for predefined time and be running some time after the predefined time has been elapsed.
    For example, a call to sleep(60) will cause the currently executing thread to sleep for 60 milliseconds. This thread will be in ready-to-run state after that. It will be in "Running" state only when the scheduler will pick it for execution. Thus we can only say that the thread will run some time after 60 milliseconds.
  • Blocked on I/O.
    A java thread may enter this state while waiting for data from the IO device. The thread will move to Ready-to-Run after I/O condition changes (such as reading a byte of data).
  • Blocked on Synchronization.
    A java thread may enter this state while waiting for object lock. The thread will move to Ready-to-Run when a lock is acquired.
  • Dead
    A java thread may enter this state when it is finished working. It may also enter this state if the thread is terminated by an unrecoverable error condition.
Thread Synchronization
Problems may occur when two threads are trying to access/modify the same object. To prevent such problems, Java uses monitors and the synchronized keyword to control access to an object by a thread.
  • Monitor
    • 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 unavailable.
    • 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.
  • Synchronized code and Locks
    • Object lock
      Each Object has a lock. This lock can be controlled by at most one thread at time. Lock controls the access to the synchronized code.
    • When an executing thread encounters a synchronized statement, it goes in blocked state and waits until it acquires the object lock. After that, it executes the code block and then releases the lock. While the executing thread owns the lock, no other thread can acquire the lock. Thus the locks and synchronization mechanism ensures proper exceution of code in multiple threading.
Thread Priority
A thread's priority is specified with an integer from 1 (the lowest) to 10 (the highest), Constants Thread.MIN_PRIORITY and Thread.MAX_PRIORITY can also be used. By default, the setPriority() method sets the thread priority to 5, which is the Thread.NORM_PRIORITY.
 
Thread aThread = Thread.currentThread();
int currentPriority;
currentPriority = aThread.getPriority();
aThread.setPriority( currentPriority + 1 );
Setting priorities may not always have the desired effect because prioritization schemes may be implemented differently on different platforms. However, if you cannot resist messing with priorities, use higher priorities for threads that frequently block (sleeping or waiting for I/O). Use medium to low-priority for CPU-intensive threads to avoid hogging the processor down.
Thread Deadlock
In multiple threading, following problems may occur.
  • Deadlock or deadly embrace occurs when two or more threads are trying to gain control of the same object, and each one has a lock on another resource that they need in order to proceed.
  • For example, When thread A waiting for lock on Object P while holding the lock on Object Q and at the same time, thread B holding a lock on Object P and waiting for lock on Object Q, deadlock occurs.
  • Please note that if the thread is holding a lock and went to a sleeping state, it does not loose the lock. However, when thread goes in blocked state, it normally releases the lock. This eliminates the potential of deadlocking threads.
  • Java does not provide any mechanisms for detection or control of deadlock situations, so the programmer is responsible for avoiding them.

Comments

hey, this article was damn good man,especially abt monitors.i was searching the internet abt monitors,FINALLY I'VE FOUND ONE, THANKS MAN !!!!


This is really cool stuff.I've bookmarked it. Gives a clear picture of thread state


Jotil. This is superb.


Hello ; Is it possible to access to the stack of thread?


please , I need an answer about The java stack strucure?


Nice information about threads... its easy to understand form the picture about thread. it will be good, if the author mention why wait(),notify(),notifyAll() methods aren't in Thread class but in Object class? Any way, thanks for the info about Thread some what brief..

bye raja.r.csp


great article... brief and explaining how everything works, exactly what i was looking for! thanks


How can notify/notifyAll possibly move thread from sleeping state to ready-to-run? May I ask what is the object to call these methods on? ^)


Thanks a lot


Cool article. Explanation is brief and informative


A really good article. But I think the diagram has a minor flaw. I am surprised why the diagram does not reflect that a thread goes to ready-to-run state from blocked state (when it gets the data if its waiting for I/O or gets the lock it was waiting for) though you mention the same in your article.


Nice nd very informative....


Can you avoid a thread to stay away from blocked Stage for long time?

My threads are staying in blocked stage for very long time when they are executing below piece of code. synchronized( ClassName.class ) { // int a = getVarId(); }

Thanks! Surbhi


The diagram has a little mistake: From "Blocked" state there is an arrow to "Running" state. It should be pointing to "Ready-to-run" when locked is obtained or data received. Anyway is an brief and excellent article.


Correct me if I'm wrong, but I think that Sleeping - ready-to-run transition has nothing to do with Object.notify() and Object.notifyAll() methods as far as a thread doesn't release its monitor on sleep.

Also the diagram lack of Running-Dead state transition caused by RuntimeExcetion.


Great Work, Threads simply explained... covering concepts of Scheduling, Synchronization, Life Cycle of thread.

Both theoritically as well as Programatically... Great work


its good one... I need more information. here it only told about thread and their communication.

i need how it work in OS. How OS treat this?.. Is JVM run their thread without support of OS?.. is it possible?...JVM also a one thread for OS. So totally how it works?.. sorry for my poor english


Diagram not quite correct. No such state as "Ready to Run." Redraw with "New" state and have start() emanate from this state (only allowable).


Perfect explain, thank you so much !


 
Page Render Time:16