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

 Lock is related with object of one class, not with the code itself.
Case Study: Crunch2.java

B. Detail of lock

Behaviour of synchronized():
  1. Every object has one lock.
  2. 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.
  3. 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.
  4. 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


Next Page