Java 无法从另一个线程获取数组

Java 无法从另一个线程获取数组,java,arrays,multithreading,Java,Arrays,Multithreading,我有一个很小但很奇怪的问题… 我需要从文件中读取片段并将它们放入数组中,这超出了读取线程的范围,但当我想从当前线程中获取它们时,我得到的是空数组。 我的大脑被这些东西震碎了: private int fragmentSize = 262144, fragmentCacheElements = 32, fragmentCacheUpdates = 0; // Cache 8Mb (265Kb*32)(262144*32) private String[] fragmentCache; privat

我有一个很小但很奇怪的问题…
我需要从文件中读取片段并将它们放入数组中,这超出了读取线程的范围,但当我想从当前线程中获取它们时,我得到的是空数组。
我的大脑被这些东西震碎了:

private int fragmentSize = 262144, fragmentCacheElements = 32, fragmentCacheUpdates = 0;
// Cache 8Mb (265Kb*32)(262144*32)
private String[] fragmentCache;
private boolean needCacheUpdate, end;
private Thread cacheThread = new Thread(new Runnable()
{
    String[] fCache = new String[fragmentCacheElements];

    @Override
    public void run()
    {
        while (!end) {
            for (int i = 0; i < fragmentCacheElements; ++i) {
                fCache[i] = new String(loadFragment(i + fragmentCacheUpdates * fragmentCacheElements));
            }
            while (true) {
                if (needCacheUpdate) {
                    ++fragmentCacheUpdates;
                    fragmentCache = fCache;
                    // fragment[0] != null
                    needCacheUpdate = false;
                    break;
                }
            }
        }
    }
});

public static void main(String[] args)
{
    fragmentCache = new String[fragmentCacheElements];
    cacheThread.start();
    updateCache();
    // Notifying client
}

// Getting fragment from cache to send it to client
// AND WHY fragment[0] == null ???
private String getCache(int id)
{
    if (id >= fragmentCacheUpdates * fragmentCacheElements) {
        updateCache();
    }
    return fragmentCache[id - (fragmentCacheUpdates - 1) * fragmentCacheElements];
}

private void updateCache()
{
    needCacheUpdate = true;
    while (true) {
        if (!needCacheUpdate) {
            break;
        }
    }
}
private int fragmentSize=262144,fragmentCacheElements=32,fragmentCacheUpdates=0;
//高速缓存8Mb(265Kb*32)(262144*32)
私有字符串[]碎片缓存;
私有布尔缓存更新,结束;
私有线程cacheThread=新线程(new Runnable()
{
String[]fCache=新字符串[fragmentCacheElements];
@凌驾
公开募捐
{
当(!结束){
对于(int i=0;i=fragmentCacheUpdates*fragmentCacheElements){
updateCache();
}
返回fragmentCache[id-(fragmentCacheUpdates-1)*fragmentCacheElements];
}
私有void updateCache()
{
needCacheUpdate=true;
while(true){
如果(!needCacheUpdate){
打破
}
}
}
有什么建议吗?

试试看

fragmentCache = Arrays.copyOf(fCache, fCache.length);

@你的意思是说,以循环的方式进行?类似于(inti=0;iAhh。。这是因为我复制了到fCache的链接,但没有复制值!你真是天才,谢谢!