Java 如何确保写入整数数组的可见性
我有一个基本类型int[][]的数组,可以是图像数据。我想在这个数组上执行一些操作,这些操作可以很容易地划分为线程来执行,结果存储在一个类型和大小相同的数组中,只对这个输出数组进行写操作。如何使用多个线程并确保在每个线程完成后,结果数组中的所有结果都是可见的?我想在这个计算之后重用线程。我如何做到这一点,下面的代码在内存可见性方面是否正确Java 如何确保写入整数数组的可见性,java,arrays,multithreading,concurrency,Java,Arrays,Multithreading,Concurrency,我有一个基本类型int[][]的数组,可以是图像数据。我想在这个数组上执行一些操作,这些操作可以很容易地划分为线程来执行,结果存储在一个类型和大小相同的数组中,只对这个输出数组进行写操作。如何使用多个线程并确保在每个线程完成后,结果数组中的所有结果都是可见的?我想在这个计算之后重用线程。我如何做到这一点,下面的代码在内存可见性方面是否正确 import java.util.ArrayList; import java.util.concurrent.ExecutionException; imp
import java.util.ArrayList;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
public class ArraySynchronization
{
public static void main(String[] args) throws InterruptedException, ExecutionException
{
final int width = 100;
final int height = 100;
final int[][] img = new int[width][height];
final int[][] avg = new int[width][height];
final int threadNo = 8;
ExecutorService pool = Executors.newFixedThreadPool(threadNo);
ArrayList<Future> futures = new ArrayList<Future>(threadNo);
for (int x = 1; x < width - 1; x++)
{
final int col = x;
Future future = pool.submit(new Runnable()
{
public void run()
{
for (int y = 1; y < height; y++)
{
avg[col][y] = (img[col - 1][y] + img[col][y] + img[col + 1][y]) / 3;
}
// how can I synchronize the data in avg[][] here?
};
});
futures.add(future);
}
// is this loop enough to ensure all data is synchronized in avg[][]?
for (Future future : futures)
{
future.get();
}
// can I read avg here, will the results be correct?
for (int x = 0; x < width; x++)
{
for (int y = 0; y < height; y++)
{
System.out.println(avg[x][y]);
}
}
pool.shutdown();
pool.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS);
// now I know tasks are completed and results synchronized (after thread death), but what if I plan to reuse the pool?
}
}
import java.util.ArrayList;
导入java.util.concurrent.ExecutionException;
导入java.util.concurrent.ExecutorService;
导入java.util.concurrent.Executors;
导入java.util.concurrent.Future;
导入java.util.concurrent.TimeUnit;
公共类阵列同步
{
公共静态void main(字符串[]args)引发InterruptedException、ExecutionException
{
最终整数宽度=100;
最终内部高度=100;
最终整数[]img=新整数[宽度][高度];
最终整数[]平均值=新整数[宽度][高度];
最终int螺纹编号=8;
ExecutorService池=Executors.newFixedThreadPool(线程号);
ArrayList futures=新ArrayList(线程号);
对于(int x=1;x
根据javadoc:
内存一致性影响:异步
计算发生在相应操作之后的操作之前
另一个线程中的Future.get()
这意味着在循环所有的Futures
并调用get()
之后,可以保证操作已经发生,并且整数数组包含结果
之后,您可以自由地重用池,而不会以任何方式影响计算的数组。同样,您可以确保任何其他写入的可见性。它是一个数组没有什么区别。