Saturday, March 2, 2013

Java Concurrency: Thread State

In Java, a thread has 5 kinds of states: NEW, RUNNABLE, BLOCKED, WAITING, TIMED_WAITING, TERMINATED. When you execute Thread.sleep(long), the current thread status will transform from RUNNABLE to TIMED_WAITING, and the current thread will give up CPU resources to another threads. But the current thread will not give up the monitor.

When execute Object.wait(), the current thread will become to WAITING state ( Object timed wait will make thread to TIMED_WAITING state ). But different with Thread.sleep(), Object.wait() will make thread to give up the monitor.

When your code use synchronized keyword try to acquire a monitor but blocked, the current thread will be at BLOCKED state. At that moment, the thread cannot respond to the interruption. But at WAITING and TIMED_WAITING state, a thread can have chance to respond to the interruption.

Different with synchronized, Lock.tryLock(long time, TimeUnit unit) can respond to the interruption. So use Lock in Java 5 concurrent is a way to avoid dead lock.

No comments:

Post a Comment