Java数组在静态方法线程中是否安全? [英] Are Java arrays in a static method thread safe?

查看:213
本文介绍了Java数组在静态方法线程中是否安全?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

   public static int rank(int key, int[] a) {
        int lo = 0;
        int hi = a.length - 1;
        while (lo <= hi) {
            // Key is in a[lo..hi] or not present.
            int mid = lo + (hi - lo) / 2;
            if      (key < a[mid]) hi = mid - 1;
            else if (key > a[mid]) lo = mid + 1;
            else return mid;
        }
        return -1;
    }

上面的静态方法进行二分查找。它是线程安全吗?我知道局部变量是线程安全的,但a这里是一个数组,所以这意味着它是Java中的一个对象,对吧?那是问题吗?
数组刚刚被读取,没有以任何方式修改,所以我假设这个方法是线程安全的。但我想确保理解为什么。

The above static method does binary search. Is it thread safe? I know that local variables are thread safe but "a" here is an array, so that means it's an object in Java, right? Is that a problem? The array is just being read, not modified in any way, so I'm assuming this method is thread-safe. But I want to make sure I understand why.

谢谢!

推荐答案

没有数组通常不是线程安全的。代码是否在这种情况下取​​决于其他线程是否可以访问您传入的数组。因为数组是通过引用传递的,所以其他线程可以访问它们。

No arrays are not generally threadsafe. Whether your code is in this case depends on whether other threads have access to the array you passed in. Because arrays are passed by reference, then other threads can have access to them.

如果你只在一个线程中创建/修改数组,或者你传入一个以线程安全的方式复制的副本就可以了。

If you only create/modify the array in a single thread, or if you pass in a copy that is copied in a threadsafe way it will be fine.

这篇关于Java数组在静态方法线程中是否安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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