gpt4 book ai didi

java - 线程安全对象数组

转载 作者:行者123 更新时间:2023-11-29 06:49:16 27 4
gpt4 key购买 nike

我在 Java 中使用二维数组。但是现在,我想将这个类用于多线程。我怎样才能做到这一点?

我知道如何实现线程安全功能(添加同步关键字)。如果同时触发 clear 和 getItem 函数会怎样?对于这种情况,我该如何做线程安全事件?

public class ThreadSafeArray {
int ROW_MAX_COUNT = 1024;

int rowCount = 0;
int counterForRow = 0;
private Object [][] objInstances = new Object[ROW_MAX_COUNT][];

public synchronized void addItem(Object obj) {
if(counterForRow == ROW_MAX_COUNT) {
objInstances[++rowCount] = new Object[ROW_MAX_COUNT];
counterForRow = 0;
}

objInstances[rowCount][counterForRow++] = obj;
}

public synchronized void clear() {
objInstances = new Object[ROW_MAX_COUNT][];
rowCount = 0;
counterForRow = 0;
}

public synchronized Object getItem(int index) {
int row = index / ROW_MAX_COUNT;
int column = index % ROW_MAX_COUNT;

if((row <= rowCount) && (column <= counterForRow)) {
return objInstances[row][column];
}
return null;
}
}

最佳答案

在您的代码中,cleargetItem 是实例方法。将 synchronized 放在实例方法上意味着线程必须在调用该方法的对象实例上获取锁(“内部锁”),然后线程才能开始执行该方法中的任何代码。

使实例方法同步有两个效果(来自 java 指南):

  • First, it is not possible for two invocations of synchronized methods on the same object to interleave. When one thread is executing a synchronized method for an object, all other threads that invoke synchronized methods for the same object block (suspend execution) until the first thread is done with the object.
  • Second, when a synchronized method exits, it automatically establishes a happens-before relationship with any subsequent invocation of a synchronized method for the same object. This guarantees that changes to the state of the object are visible to all threads.

因此,您的类对于这两个方法已经是线程安全的。

关于java - 线程安全对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54800866/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com