【发布时间】:2010-02-26 08:15:32
【问题描述】:
我有一个与我在这里的第一个问题相关但不完全相同的问题:
Java: what happens when a new Thread is started from a synchronized block?
当您持有锁时,创建和start() 一个新的Thread 是一种常见的做法吗?
那会是代码味道吗?
基本上我可以选择这样做:
public synchronized void somemethod() {
(every time I find a callback to be notified I start a thread)
Thread t = new Thread( new Runnable() {
void run() {
notifySomeCallback();
}
}
t.start();
...
(lengthy stuff performed here, keeping the lock held)
...
}
或者这个:
public void somemethod() {
(create a list of callbacks to be notified)
synchronized(this){
(potentially add callbacks)
...
(lengthy stuff performed here, keeping the lock held)
...
}
(notify the callbacks without holding a lock and once
we know the lock has been released)
}
我认为后者更好,但我想知道是否有 是第一个选项可以的情况吗?你有时会 去做?你见过吗?
【问题讨论】:
标签: java multithreading locking callback