标签:ane cas syn add div and 第一个 har 解决方案
public synchronized void put(String value) throws InterruptedException{ while (buffer.size() == capacity) { System.out.println(Thread.currentThread().getName() + " is waiting..."); wait(); } buffer.add(value); System.out.println(Thread.currentThread().getName() + " has produced " + value); notify(); } public synchronized String get() throws InterruptedException{ while (buffer.size() == 0) { System.out.println(Thread.currentThread().getName() + " is waiting..."); wait(); } String val = buffer.remove(0); notify(); System.out.println(Thread.currentThread().getName() + " has consumed " + val); return val; }
while
loop in case we get this situation:
STEP 1:
- P1 puts 1 char into the buffer
STEP 2:
- P2 attempts put
- checks wait loop - already a char - waits 【P2在等待】
STEP 3:
- P3 attempts put
- checks wait loop - already a char - waits 【P2、P3在等待】
STEP 4:
- C1 attempts to get 1 char
- C2 attempts to get 1 char - blocks on entry to the get
method 【C2阻塞】
- C3 attempts to get 1 char - blocks on entry to the get
method 【C2、C3阻塞】
STEP 5:
- C1 is executing the get
method - gets the char, calls notify
, exits method
- The notify
wakes up P2
- BUT, C2 enters method before P2 can (P2 must reacquire the lock), so P2 blocks on entry to the put
method 【P3等待】【P2、C3阻塞】
- C2 checks wait loop, no more chars in buffer, so waits 【P3、C2等待】【P2、C3阻塞】
- C3 enters method after C2, but before P2, checks wait loop, no more chars in buffer, so waits 【C3、C2、P3等待】【P2阻塞】
STEP 6:
- NOW: there is P3, C2, and C3 waiting!
- Finally P2 acquires the lock, puts a char in the buffer, calls notify, exits method 【P2终于抢占了锁】
STEP 7:
- P2‘s notification wakes P3 (remember any thread can be woken) 【P3被notified】
- P3 checks the wait loop condition, there is already a char in the buffer, so waits. 【P3、C2、C3等待】【阻塞队列为空】
- NO MORE THREADS TO CALL NOTIFY and THREE THREADS PERMANENTLY SUSPENDED!
标签:ane cas syn add div and 第一个 har 解决方案
原文地址:http://www.cnblogs.com/wttttt/p/6978054.html