如何在 java 中制作线程安全的行矩阵
how to make thread-safe row matrix in java
我有一个问题:我有一个表示 int 矩阵的结构。我必须对该矩阵的单行执行一些操作,并且该操作必须是线程安全的。
我想锁定整个矩阵,但我只想锁定单行。
我怎样才能做到这一点???谢谢
你必须保留一个数组来存储当前繁忙的行号。每次访问一行时,您都必须调用一个函数来填充此数组,以防止其他人访问同一行。如果您完成对特定行的处理,您将从数组中删除行号,以便其他人可以再次访问它。
Java 实际上本身并不支持多维数组。二维数组只是数组的数组。
因此,您可以在单行上进行同步:
synchronized(matrix[row_index]) {
// do stuff with matrix[row_index] here
}
这是假设没有其他代码重新分配 matrix[row]
(数组本身,而不是元素);如果可以,那么你需要一个临时变量来避免竞争条件,在这种情况下另一个线程可能会在你的 synchronized
块的中间重新分配它:
int[] the_row = matrix[row_index];
synchronized(the_row) {
// do stuff with the_row here (NOT matrix[row_index])
}
或者,您可以使用单独的锁对象数组:
// a field in your Matrix class
Object[] row_locks;
// initialized like this (probably in your constructor, or whenever the matrix is resized)
for(int row_index = 0; row_index < number_of_rows; row_index++)
row_locks[row_index] = new Object();
// and used like this:
synchronized(row_locks[row_index]) {
// do stuff with the row_index'th row here
}
我有一个问题:我有一个表示 int 矩阵的结构。我必须对该矩阵的单行执行一些操作,并且该操作必须是线程安全的。 我想锁定整个矩阵,但我只想锁定单行。 我怎样才能做到这一点???谢谢
你必须保留一个数组来存储当前繁忙的行号。每次访问一行时,您都必须调用一个函数来填充此数组,以防止其他人访问同一行。如果您完成对特定行的处理,您将从数组中删除行号,以便其他人可以再次访问它。
Java 实际上本身并不支持多维数组。二维数组只是数组的数组。
因此,您可以在单行上进行同步:
synchronized(matrix[row_index]) {
// do stuff with matrix[row_index] here
}
这是假设没有其他代码重新分配 matrix[row]
(数组本身,而不是元素);如果可以,那么你需要一个临时变量来避免竞争条件,在这种情况下另一个线程可能会在你的 synchronized
块的中间重新分配它:
int[] the_row = matrix[row_index];
synchronized(the_row) {
// do stuff with the_row here (NOT matrix[row_index])
}
或者,您可以使用单独的锁对象数组:
// a field in your Matrix class
Object[] row_locks;
// initialized like this (probably in your constructor, or whenever the matrix is resized)
for(int row_index = 0; row_index < number_of_rows; row_index++)
row_locks[row_index] = new Object();
// and used like this:
synchronized(row_locks[row_index]) {
// do stuff with the row_index'th row here
}