我有一个问题与我在这里的第一个问题相关但不完全相同:
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)
}
我认为后者更好,但我想知道是否有 在第一个选项可以的情况下?你有时 去做?你见过吗?
最佳答案
回答3:
您应该始终尽可能短地持有一把锁。因此,当存在“损坏”资源的可能性时(例如,编写器线程正在更新资源),只有可能从多个线程引用的资源应该被锁定最短的时间
不要为每件需要完成的小事分拆一个线程。对于回调线程,让 1 个回调线程处理待办事项队列。
关于Java:持有锁时创建新线程是常见的做法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2340267/