java编程思想中的一段代码:
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();
}
}
}class ExplicitPairManager2 extends PairManager
{
private ReentrantLock lock = new ReentrantLock();
public void increment()
{
Pair temp;
lock.lock();
try
{
p.incrementX();
p.incrementY();
temp = getPair();
}
finally
{
lock.unlock();
}
store(temp); // 在临界区外
}
}两个类继承同一个抽象类,并实现了其increment方法,第一个类的increment定义成synchronized的,同时用了Lock加锁,
第二个类的increment方法没有定义成synchronized的,但也用了Lock加锁,我想问的是,既然第一个类的increment方法已经用了Lock对临界区加锁,那方法定义成synchronized的,还有必要吗?
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();
}
}
}class ExplicitPairManager2 extends PairManager
{
private ReentrantLock lock = new ReentrantLock();
public void increment()
{
Pair temp;
lock.lock();
try
{
p.incrementX();
p.incrementY();
temp = getPair();
}
finally
{
lock.unlock();
}
store(temp); // 在临界区外
}
}两个类继承同一个抽象类,并实现了其increment方法,第一个类的increment定义成synchronized的,同时用了Lock加锁,
第二个类的increment方法没有定义成synchronized的,但也用了Lock加锁,我想问的是,既然第一个类的increment方法已经用了Lock对临界区加锁,那方法定义成synchronized的,还有必要吗?
解决方案 »
免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货