同步分量以阵列 [英] Synchronizing elements in an array

查看:174
本文介绍了同步分量以阵列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新来的多线程Java和不明白发生了什么事情。

I am new to multi-threading in Java and don't quite understand what's going on.

从在线教程和讲义,我知道同步块,它必须适用于一个非空的对象,确保只有一个线程可以执行该块的code。因为阵列是Java对象,同步可应用于它。另外,如果阵列存储对象,我应该能够对数组的每个元素也同步。

From online tutorials and lecture notes, I know that the synchronized block, which must be applied to a non-null object, ensures that only one thread can execute that block of code. Since an array is an object in Java, synchronize can be applied to it. Further, if the array stores objects, I should be able to synchronize each element of the array too.

我的计划已经几个线程更新数字数组,所以我创建对象的数组:

My program has several threads updated an array of numbers, hence I created an array of Long objects:

synchronized (grid[arrayIndex]){
    grid[arrayIndex] += a.getNumber();
}

这code坐镇中运行()我已经扩展了Thread类的方法。该阵列,网格,由所有线程我共享。然而,在一个线程运行同一程序,而这并不能返回正确的结果呢。

This code sits inside the run() method of the thread class which I have extended. The array, grid, is shared by all of my threads. However, this does not return the correct results while running the same program on one thread does.

推荐答案

这是行不通的。要认识到电网[arrayIndex] + = ... 实际上是替换在电网的元素是很重要的与的新对象。这意味着正在同步的阵列中的一个物体上,然后立即用另一个替换阵列中的对象。这将导致其他线程锁定不同的物体上,这样他们就不会阻塞。您的必须的对锁的的对象。

This will not work. It is important to realize that grid[arrayIndex] += ... is actually replacing the element in the grid with a new object. This means that you are synchronizing on an object in the array and then immediately replacing the object with another in the array. This will cause other threads to lock on a different object so they won't block. You must lock on a constant object.

您可以将整个数组对象上,而不是锁定,的如果的它都不会与另一个数组对象代替:

You can instead lock on the entire array object, if it is never replaced with another array object:

synchronized (grid) {
    // this changes the object to another Long so can't be used to lock
    grid[arrayIndex] += a.getNumber();
}

这是原因之一,为什么它是一个很好的模式来锁定一个最后对象。看到这个答案与更多的细节:

This is one of the reasons why it is a good pattern to lock on a final object. See this answer with more details:

<一个href=\"http://stackoverflow.com/questions/10324272/why-is-it-not-good-practice-to-synchronize-on-boolean/10324280#10324280\">Why岂不是很好的做法,布尔同步?

这篇关于同步分量以阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆