10. Interactive among threads
What's the problem.
Case Study: Crunch.java
In some critical status, other threads are not allowed to access data.
Code section when data in such critical status is called critical section.
A. Object lock
synchronized (object) {
//
}
Lock is related with object of one class, not with the code itself.
Case Study: Crunch2.java
B. Detail of lock
Behaviour of synchronized():
-
Every object has one lock.
-
To excute synchronized() block, the thread should get the lock of the object.
After the thread take the lock, the object no longer has it.
-
If when the thread start to excute synchronized(), the lock is not in the
object, the thread stalls till the lock returns to the object and is taken
by the thread.
-
When the thread leave the synchorized() block, the lock is returned to
the object.
synchronized() is not to protect data, but is to prevent more than one
thread excuteing in one time.
C. Synchronized method
void method() {
synchronized(this) {
//
}
}
==
synchronized void method() {
//
}
D. Nested synchronized