第四版 Critical sections部分:
You can also use explicit Lock objects to create critical sections:
[code="java"]//: concurrency/ExplicitCriticalSection.java
// Using explicit Lock objects to create critical sections.
package concurrency;
import java.util.concurrent.locks.*;
// Synchronize the entire method:
class ExplicitPairManager1 extends PairManager {
private Lock lock = new ReentrantLock();
public synchronized void increment() {
lock.lock();
try {
p.incrementX();
p.incrementY();
store(getPair());
} finally {
lock.unlock();
}
}
// Use a critical section:
class ExplicitPairManager2 extends PairManager {
private Lock lock = new ReentrantLock();
public void increment() {
Pair temp;
lock.lock();
try {
p.incrementX();
p.incrementY();
temp = getPair();
} finally {
lock.unlock();
}
store(temp);
}
}
public class ExplicitCriticalSection {
public static void main(String[] args) throws Exception {
PairManager
pman1 = new ExplicitPairManager1(),
pman2 = new ExplicitPairManager2();
CriticalSection.testApproaches(pman1, pman2);
}
} /* Output: (Sample)
pm1: Pair: x: 15, y: 15 checkCounter = 174035
pm2: Pair: x: 16, y: 16 checkCounter = 2608588
*///:~
[/code]
这段代码书里的,只是把synchronized 换成lock 实现,但是 我的运行结果每次会出现:
[color=red]---------- JAVA ----------
Exception in thread "pool-1-thread-4" Pair$PairValuesNotEqualException: Pair values not equal: x: 2, y: 1
at Pair.checkState(ExplicitCriticalSection.java:32)
at PairChecker.run(CriticalSection.java:101)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
at java.lang.Thread.run(Thread.java:619)[/color]
pm1: Pair: x: 11, y: 11 checkCounter = 3134
pm2: Pair: x: 12, y: 12 checkCounter = 1388632
谁能告诉我问什么这里有异常吗?按书里说是不会的!
哇 这个问题javaeye里居然有人问过,但没人回,郁闷啊,我问题跟他一摸一样[url=/topic/221693]http://www.iteye.com/topic/221693[/url]