同步,何时使用? [英] Synchronization, When to or not to use?

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

问题描述

我已经开始学习Java中的并发和线程。我知道同步的基础知识(即它的作用)。从概念上讲,我理解它提供了对Java中多个线程的共享资源的互斥访问。但是当面对像下面这样的例子时,我很困惑,让它同步是否是一个好主意。我知道代码的关键部分应该是同步的,这个关键字不应该被过度使用,否则会影响性能。

I have started learning concurrency and threads in Java. I know the basics of synchronized (i.e. what it does). Conceptually I understand that it provides mutually exclusive access to a shared resource with multiple threads in Java. But when faced with an example like the one below I am confused about whether it is a good idea to have it synchronized. I know that critical sections of the code should be synchronized and this keyword should not be overused or it effects the performance.

public static synchronized List<AClass> sortA(AClass[] aArray) 
{
    List<AClass> aObj = getList(aArray);

    Collections.sort(aObj, new AComparator());

    return aObj;
}

public static synchronized List<AClass> getList(AClass[] anArray) 
{
    //It converts an array to a list and returns
}


推荐答案

假设每个线程通过一个不同的数组,则不需要同步,因为其余变量是本地的。

Assuming each thread passes a different array then no synchronization is needed, because the rest of the variables are local.

如果你取消了几个线程全部调用 sortA 并将引用传递给同一个数组,你遇到麻烦没有 synchronized ,因为它们会互相干扰。

If instead you fire off a few threads all calling sortA and passing a reference to the same array, you'd be in trouble without synchronized, because they would interfere with eachother.

当心,从示例中可以看出, getList 方法从数组中返回一个新的 List ,这样即使线程传递相同的数组,你得到不同的 List 对象。这是误导。例如,使用 Arrays.asList 创建一个由给定数组支持的 List ,但javadoc明确指出对返回列表的更改直写到数组。所以要小心。

Beware, that it would seem from the example that the getList method returns a new List from an array, such that even if the threads pass the same array, you get different List objects. This is misleading. For example, using Arrays.asList creates a List backed by the given array, but the javadoc clearly states that Changes to the returned list "write through" to the array. so be careful about this.

这篇关于同步,何时使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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