并发访问数组而没有安全性

时间:2018-12-25 14:41:13

标签: java concurrency

field的值是float [],我在调试代码时感到困惑,因为一个线程正在工作并且使用我的float [] values数组时,其他线程正在等待它正常吗?我不在乎数组上的错误数据,因为线程正在计算数组的不同部分

ExecutorService executor = Executors.newFixedThreadPool(threads);

List<PartOfImage> callables;
        for(int j=0;j<200;++j)
        for(int i=0;i<threads;++i){
            callables=new LinkedList<>();
            callables.add(new PartOfImage(values,width,(height/threads)*i, (height/threads)*(i+1),
                    oldImage,((i+1)%threads)==0,(i%threads)==0));

        List<Future<Object>> answers =   executor.invokeAll(callables);


         oldImage=getValues();
        }

1 个答案:

答案 0 :(得分:0)

假设您的.table .card-container.fadeOut { transition: background-color 1s ease-out 1s; } 是10。您可能认为您的代码在threads列表中生成10个可调用对象,然后运行callables。但实际上,您的代码为每个invokeAll执行了整个代码块:

i

这意味着它将创建一个包含一个可调用项的列表,然后在该列表上运行callables=new LinkedList<>(); callables.add(new PartOfImage(values,width,(height/threads)*i, (height/threads)*(i+1), oldImage,((i+1)%threads)==0,(i%threads)==0)); List<Future<Object>> answers = executor.invokeAll(callables); oldImage=getValues(); ,然后转到下一个invokeAll,创建一个包含一个可调用项的列表,然后在该列表上运行i (单任务)列表,等等。

因此实际上它是串行运行的。您应该将列表的创建移到invokeAll循环之外,只有i应该在循环内部,而callables.addinvokeAll应该在循环之外。 / p>

相关问题