Java threads
Thread Creation
There are two ways to create a thread.
1. Extend the java.lang.Thread class.
2. Implement the java.lang.Runnable interface.
Thread states
A thread can be in one of the following states:
- A thread that has not yet started is in this state.
- A thread executing in the Java virtual machine is in this state.
- A thread that is blocked waiting for a monitor lock is in this state.
- A thread that is waiting indefinitely for another thread to perform a particular action is in this state.
- A thread that is waiting for another thread to perform an action for up to a specified waiting time is in this state.
- A thread that has exited is in this state.
A thread can be in only one state at a given point in time. These states are virtual machine states which do not reflect any operating system thread states.
Thread synchronization
java provides built-in locking mechanism for securing exclusive access to an object through the synchronized modifier. java also provides Concurrency Utilities which include better locks. so whenever possible we should these locks.
Following are two mechanisms which use synchronized modifier to write thread safe code-
Method Synchronization
Every Java object has an intrinsic lock. To acquire an object's intrinsic lock is the same as locking the object. When we use the synchronized modifier for a method then we basically lock the object for the current thread. no other thread can access the method or any other synchronized method on the object. this is object level locking. if the method is static the lock is applicable at class level , which means, no other thread can access any synchronized method of any object of the class.
Block Synchronization
Synchronizing a method is not always possible for various reasons. for example we may not have access to the source code of the class. Java allows us to lock any object through block synchronization. Its syntax is this -
synchronized(object) {
// do something while locking the object
}On other note, method synchronization is the same as block synchronization that locks the current object:synchronized(this) {
...
}Visibility
Due to the memory model in Java, a thread may not see changes made by another thread unless the operations that act on the data are synchronized. To solve this problem a variable can be declared as volatile.
Comments
Post a Comment