作者adrianshum (Alien)
看板java
标题Re: [问题] synchronized 和 multi thread
时间Wed Oct 5 11:44:55 2011
※ 引述《jehovah (Lucius)》之铭言:
: 大家好, 小弟对multi thread还不熟悉, 想请教一个问题
: 目前我有A, B两条thread, 以及一个公用的arraylist
: A thread会做以下的工作:
: arraylist.remove(old_index);
: ...一些运算
: arraylist.add(new_index, obj);
: B thread则会对arraylist作get
: 因此A在作add前, B有机会IndexOutOfBounds
: 我查了synchronized修饰字,
: 将A的工作用synchronized包起来, 可是没有帮助
: synchronized(arraylist){
: ...
: }
: 我是希望锁住arraylist这个物件, 而不是操作这物件的Method
: 请问一般来说, 这种状况如何处理较恰当?
: 可否给我点建议, 或是该往哪个方向去查..谢谢:)
虽然看不很懂你想做的是什麽,不过看来你是误会了
synchronized (或其他locking 方法)的用意。
(看来其他人也没有提及)
你不止要把 A 的工作 synchronized ,B 也需要。
synchronized 可以想成是一个协同方法而已,并
不是你把 A 的工作利用 synchronized 包起来就
行,B 做的动作 (比如你说的 get ) 也要
synchronize,B 才会乖乖等 A 相关的动作做完
才执行。
比如:
A:
synchronized(arrayList) {
arrayList.remove(something);
// do something else
arrayList.add(something);
}
B:
synchronized(arrayList) {
arrayList.get(index);
}
这样才行。
搞清楚这里,就可以再下一步了:
利用 concurrent package 的 lock 的概念也类似,
只是 lock & unlock 要explictly 做,而做 lock
的目标也不是 arrayList 本身,而是一个 “代表”
arrayList 的 lock obj:
A:
arrayListLock.lock();
try {
arrayList.remove(something);
// do something else
arrayList.add(something);
} finally {
arrayListLock.unlock();
}
B:
arrayListLock.lock();
try {
arrayList.get(index);
} finally {
arrayListLock.unlock();
}
这步搞得通吗?
搞得通的话,再下一步:
你写的东西,如果将来会常有多 thread 一起读 (B),
偶然才会 update (A),那麽用 reader writer lock
是一个好选择:
A:
// ReadWriteLock arrayListLock
arrayListLock.writeLock().lock();
try {
arrayList.remove(something);
// do something else
arrayList.add(something);
} finally {
arrayListLock.writeLock()unlock();
}
B:
arrayListLock.readLock().lock();
try {
arrayList.get(index);
} finally {
arrayListLock.readLock().unlock();
}
这一步还可以吗?
然後到最後一步。
虽然到处都自己 lock 是可以跑,但 maintain
起来可不是一件好事。视乎你的设计,你可以
考虑大家不是直接操作 arrayList, 而是把相
关的 business logic 包起来。比如,arrayList
放的是学生资料,那麽,倒不如弄一个 StudentRepository.
各 thread 是操作 StudentRepository:
interface StudentRepository {
void updateStudent(Student student);
Student getStudent(int index);
}
class StudentRepositoryImpl implements StudentRepository {
List<Student> students;
ReadWriteLock repoLock;
public void updateStudent(Student student) {
// 就是本来在 A 里面操作 arrayList 的逻辑
repoLock.writeLock().lock();
try {
students.remove(something);
// do something else
students.add(something);
} finally {
repoLock.writeLock().unlock();
}
}
public Student getStudent(int index) {
// 本来在 thread B 里操作arraylist 的部份
repoLock.readLock().lock();
try {
return students.get(index);
} finally {
repoLock.readLock.unlock();
}
}
}
A:
repo.updateStudent(student);
//其他有的没的
B:
student = repo.getStudent(i);
// 对 student 作其他操作 etc.
这样既可把 arrayList 的操作包起来,你也可以随便
选用/改用 synchronization 的策略 (直接用 synchronized,
或用 ReentrantLock, 或用 Reader Writer Lock etc)
。整体设计更是整齐许多.
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 183.179.61.91
1F:推 jehovah:谢谢这麽详细的解说! 我来仔细看一看^^ 10/05 14:17
2F:推 mahotaco:受用! 没GP可奉上,感谢之意请收下。 10/06 10:20
3F:推 AI3767:显而易懂, 受益良多 ^^ 10/06 12:31