我试图锁定对象但没有结果
在这种情况下如何处理锁定?
编辑:
根据评论,我决定不再发布带有代码的问题。它不是复制和粘贴然后运行并检查编译器说的。
不是专注于这个问题,而是人为地创造一个问题,而不是面对我所面临的问题。
我可以使用锁写入或重新锁定...而不是同步块...
我需要“手拉手”还是“锁链”?
甚至使用信号量?
EDIT2:
我有什么:
我的所作所为:
其他帖子T:
我想要实现的目标:
换句话说,在对正在进行的对象进行修改时阻止object = null
我是否需要使用某些标记 X 正在修改?
我不想要的东西:
并
@downvoter:小心解释你的投票!请
答案 0 :(得分:0)
确定!我已经挖掘了足够的信息来解决我的问题:
这里最好的方法是使用
包 java.util.concurrent.locks 提供的接口ReadWriteLock
与实施:
<强> ReentrantReadWriteLoc 强>
这里是&#34;简单&#34;示例示例:
/**
* define modifiable dog
*/
public class Dog {
private ReadWriteLock _dogLock;
private String _name;
public Dog(ReadWriteLock dogLock) {
_dogLock = dogLock;
}
public Lock dogChangesLock() {
return _dogLock.writeLock();
}
public void setName(String name) {
_dogLock.writeLock().lock();
try {
_name = name;
} finally {
_dogLock.writeLock().unlock();
}
}
public String getName() {
_dogLock.readLock().lock();
try {
return _name;
} finally {
_dogLock.readLock().unlock();
}
}
}
/**
* holder class for dog handling
*/
public class Holder {
private Dog _dog;
/**
* EURECA! this is what we want to use
*/
private ReadWriteLock _dogLock = new ReentrantReadWriteLock();
/**
* get dog
*/
public Dog getDog() {
_dogLock.readLock().lock();
try {
if (_dog == null) {
_dog = new Dog(_dogLock);
}
return _dog;
} finally {
_dogLock.readLock().unlock();
}
}
/**
* utilize dog :)
*/
private void resetDog() {
_dogLock.readLock().lock();
try {
_dog = null;
} finally {
_dogLock.writeLock().unlock();
}
}
}
/**
* test class for simultaneous write/read
*/
public class Concurent {
Holder holder = new Holder();
/**
* run concurrent threads
*/
private void test() {
/** thread for dog modification */
new Thread(new Runnable() {
/** thread to utilize dog :) */
final Thread resetThread = new Thread(new Runnable() {
@Override
public void run() {
holder.resetDog();
}
});
/** main method */
@Override
public void run() {
/** get dog */
Dog dog = holder.getDog();
/** get lock for write */
dog.dogChangesLock().lock();
try {
/** modifies dog */
dog.setName("Cat");
/** call to reset dog */
resetThread.start();
/**
* SAFE TO CALL SECOND TIME
* we don't need to check if dog was altered
* as we got write lock
* */
dog.setName("Elephant");
} finally {
dog.dogChangesLock().unlock();
}
}
}).start();
}
}