我有一类任务管理阶层,其种类如下:
public static int[][][] tasks;
我基本上可以进入这样的牢房:
synchronized(tasks[A][B]) {
// Doing something with tasks[A][B][0]
}
我的问题是,如果我这样做的话:
synchronized(tasks[A]) {
// ...
}
will it also block threads trying to enter synchronized(tasks[A][B])?
In other words, does a synchronized access to an array also synchronizes the accsess to it s cells?
If not, how to I block the WHOLE array of tasks[A] for my thread?
Edit: the answer is NO. When someone is in a synchronized block on tasks[A] someone else can simultaniously be in a synchronized block on tasks[A][B] for example - because it s a different object. So when talking about accessing objects from one place at a time, arrays are no different: to touch object X from one place at a time you need to surround it by synchronized(X) EVERYWHERE you touch it.