简体   繁体   English

ExecutorService 中的 Task 对象是如何处理的?

[英]How are Task's objects in ExecutorService handled?

I'm trying to write in parallel an image which gets modified each iteration of a loop.我正在尝试并行编写一个图像,该图像在循环的每次迭代中都会被修改。 The code looks like:代码如下:

ExecutorService pool = Executors.newFixedThreadPool(8);
for (int i = array.length - 1; i > 0; i--) 
{
            pool.execute(() -> {
                ImageIO.write(bufferedImage, "JPG", fileName + i);
            });
            //Operations on the image...
}

The problem is that the image gets written just at its initial state (i=array.length) and at its final (i=1) , but it actually writes the numbers of files it should (array.length times) .问题是图像仅在其初始 state (i=array.length)最终(i=1)写入,但它实际上写入了它应该写入的文件数(array.length times) So my question is, do I have to synchronize something on the image I'm writing?所以我的问题是,我是否必须在我正在写的图像上同步一些东西? Aren't the objects state snapshotted and saved in memory once the Task gets into the queue?一旦任务进入队列,对象 state 是否已快照并保存在 memory中? Or do tasks get the state of the object at the time of their actual execution?还是任务在实际执行时获得 object 的 state?

Task get state on moment of execution.任务在执行时得到 state。

There is no straightforward way to get snapshot of object in java.没有直接的方法可以在 java 中获取 object 的快照。

You are changing the image before each Runnable has an opportunity to save the state of the image at the time you set up the sub-task.您正在更改图像,然后每个Runnable都有机会在您设置子任务时保存图像的 state。 To avoid this problem you could make a copy of the image before setting up each runnable as follows:为避免此问题,您可以在设置每个可运行对象之前制作图像副本,如下所示:

BufferedImage imageCopy = copyImage(bufferedImage);
pool.execute(() -> {
    ImageIO.write(imageCopy, "JPG", fileName + i);
});

See these answers for possible implementations of copyImage(BufferedImage) and conditions / restrictions: Clone image How to clone image有关copyImage(BufferedImage)的可能实现和条件/限制,请参阅这些答案: Clone image How to clone image

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

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