首页 > 解决方案 > 将变量传递给 Runnable 在下一行设为 null 之前为 null

问题描述

我有一个 Runnable 类和一个单独的类,我将一个变量传递给 Runnable (ArrayList)。如果我不清空数组列表(下面的第 3 行),它会按预期运行,但是在启动线程后清空数组列表时,它在线程中是空的吗?代码执行应运行为:

Line 1 - ArrayList -> full
Line 2 - Thread start and ArrayList is passed into the thread
Line 3 - ArrayList -> empty

可运行:

public class RunnableDatabaseUpdater implements Runnable  {

    private Thread _t;
    private ArrayList<DatabaseQueueObject> _dbList;

    RunnableDatabaseUpdater(ArrayList<DatabaseQueueObject> databaseQueue) {
        _dbList = databaseQueue;
    }

    @Override
    public void run() {
        System.out.println("Thread running..");

        for (DatabaseQueueObject f : _dbList) {
            System.out.println("Datbase query in queue from the thread: " + f.getdatabaseInteractionType() + ", query: " + f.getdatabaseQuery());
        }

        System.out.println("Thread DB queue exiting..");
    }

    public void start () {
        if (_t == null) {
            _t = new Thread (this);
            _t.start ();
        }
    }
}

调用类:

    if(_masterDatabaseQueue.isEmpty()) return; // empty so return

    else
    {
        System.out.println("Starting database scheduled update..");

        RunnableDatabaseUpdater dbUpdater = new RunnableDatabaseUpdater(_masterDatabaseQueue);
        dbUpdater.start();

        // now the thread is running empty the queue so it may be used immediately for the next update cycle
        this._emptyDatabaseQueue();

    }
}

在上面的示例中(我希望它如何工作),当通过 if(_dbList.isEmpty()) 检查时返回 true。

为什么线程在清空之前会占用一个空的 ArrayList?在将 ArrayList 发送到新线程之前,我检查了它是否包含我期望的内容。

谢谢!

标签: javamultithreading

解决方案


我认为这是一个同步问题,使用 Thread.join() 可以解决这个问题!


推荐阅读