【发布时间】:2011-07-14 18:47:19
【问题描述】:
假设我在某个线程内执行synchronized 代码块,在synchronized 块内我调用一个方法,该方法生成另一个线程来处理需要与第一个方法相同的锁的同步代码块。所以在伪Java代码中:
public void someMethod() {
synchronized(lock_obj) {
// a whole bunch of stuff...
// this is the last statement in the block
(new Thread(someOtherMethod())).start();
}
// some more code that doesn't require a lock
}
public void someOtherMethod() {
// some setup code that doesn't require a lock
// return the stuff we want to run in another thread
// that does require a lock
return new Runnable() {
@Override
public void run() {
synchronized(lock_obj) {
// some more code
}
}
};
}
我不知道如何理解该代码。我写的东西合法吗?从语法上看,我没有看到任何问题,但我不确定如何通过这样的代码进行推理。那么当我执行someOtherMethod() 以创建Runnable 的实例时,return 语句之前的代码会在什么样的范围内运行?它是否作为第一个同步块的一部分执行?假设还有一些其他线程也在工作,可能需要锁定lock_obj。
【问题讨论】:
标签: java multithreading concurrency deadlock synchronized