简体   繁体   English

二维AtomicInteger数组

[英]Two Dimensional AtomicInteger array

Hey so I'm wondering how can I make AtomicInteger a two dimensional array, From what I've found on javadocs AtomicIntegerArray is only single dimension. 嘿所以我想知道如何使AtomicInteger成为一个二维数组,从我在javadocs上发现的AtomicIntegerArray只是单维。

int[] newArray = new int[100];
AtomicIntegerArray atomicarray = new AtomicIntegerArray(newArray);

Which creates a AtomicIntegerArray of size 100. But I would like an atomicarray with two dimensions. 这会创建一个大小为100的AtomicIntegerArray。但我想要一个具有两个维度的原子阵列。 I've tried doing.. 我试过做..

AtomicInteger[][] atomicArray = new AtomicInteger[100][100];
atomicArray[00][00].set(1);

But I am met with.. 但我遇到了......

java.lang.NullPointerException at nz.ac.massey.threadpool.MyClass.(MyClass.java:20) nz.ac.massey.threadpool.MyClass上的java.lang.NullPointerException。(MyClass.java:20)

So any ideas? 那么任何想法? thanks! 谢谢! :)... I haven't done much work with Atomic variables before. :)我之前没有做过很多关于原子变量的工作。

if this isn't possible how can I minimic a regular primitive integer two dim array into a AtomicInteger two dim array? 如果这是不可能的,我怎样才能将一个常规的原始整数二个dim数组最小化成一个AtomicInteger两个dim数组?

Just create a one-dimensional array of length m * n , you then need a function that maps a pair of integers (i, j) to one integer. 只需创建一个长度为m * n的一维数组,然后需要一个将一对整数(i, j)映射到一个整数的函数。 i * n + j is a good start. i * n + j是一个好的开始。 Assuming m is the number of rows and n the number of columns. 假设m是行数, n是列数。

It is a good idea to keep all of your integers inside the AtomicIntegerArray. 将所有整数保留在AtomicIntegerArray中是个好主意。 Or you'll have to deal with concurrency your self. 或者你必须处理你自己的并发。

You need to instantiate all of the positions in the matrix before accessing them, something like this: 在访问矩阵之前,您需要实例化矩阵中的所有位置,如下所示:

atomicArray[i][j] = new AtomicInteger();

Or this, if you want to initialize each atomic integer in a certain initial value: 或者,如果要初始化某个初始值中的每个原子整数:

atomicArray[i][j] = new AtomicInteger(initialValue);

That, for all i,j positions in the matrix. 对于所有i,j矩阵中的i,j位置。 Normally you'd do this using a couple of nested for loops: 通常你会使用几个嵌套for循环来做到这一点:

for (int i = 0; i < 100; i++) {
    for (int j = 0; j < 100; j++) {
        atomicArray[i][j] = new AtomicInteger();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM