坚持从另一个线程获取数组

时间:2014-02-22 03:22:45

标签: java arrays multithreading

我有一个小但很奇怪的问题...... 我需要从文件中读取片段并将它们放入数组中,这不是读取线程,但是当我想从当前线程中获取它们时,我得到空的arrray。
我的大脑在这件事上崩溃了:

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;
        }
    }
}

有什么建议吗?

1 个答案:

答案 0 :(得分:1)

尝试

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