【问题标题】:Passing variable to Runnable is null BEFORE the next line where it is made null将变量传递给 Runnable 在下一行变为 null 之前为 null
【发布时间】:2020-10-28 14:19:35
【问题描述】:

我有一个 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 发送到新线程之前,我已经检查了它是否包含我期望的内容。

谢谢!

【问题讨论】:

    标签: java multithreading


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2010-10-09
      • 1970-01-01
      • 2014-11-30
      • 2013-12-29
      • 1970-01-01
      • 2017-01-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多