java - 将变量传递给 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 发送到新线程之前,我检查了它是否包含我期望的内容。
谢谢!
解决方案
我认为这是一个同步问题,使用 Thread.join() 可以解决这个问题!
推荐阅读
- python - 混合理解(异步 + 同步)在 Python 中无法按预期工作
- c - 如何修复警告:C4129 'e':无法识别的字符转义序列
- graphql - 未调用嵌套的 GraphQL 解析器
- javascript - 在 React Native 中关闭键盘
- python - 在 STFT 图中找到一个点
- xero-api - 尝试创建 XERO APP 时出现错误:无法创建应用程序 #07D4
- c# - 如何使用 keyvault 证书获取可重复的 HMAC 哈希
- gatsby - github页面脚本仅在自定义域上不加载
- linux - 在我的 Xampp localhost ubuntu linux 中哪里可以找到 .htaccess 文件
- javascript - 使用带有 HTML 下拉选择的 Javascript