Android查询修改UI线程中的变量
我有一个简单的查询返回一个游标,然后我遍历游标并创建我在ArrayList中抛出的对象,如下所示:Android查询修改UI线程中的变量,android,multithreading,Android,Multithreading,我有一个简单的查询返回一个游标,然后我遍历游标并创建我在ArrayList中抛出的对象,如下所示: List<Element> myElements = new ArrayList<Element>(); Cursor c = db.query(...); c.moveToFirst(); while (c != null && !c.isAfterLast()) { myElements.add(new Element(curso
List<Element> myElements = new ArrayList<Element>();
Cursor c = db.query(...);
c.moveToFirst();
while (c != null && !c.isAfterLast()) {
myElements.add(new Element(cursor.getString(0).........)); <-- CREATING THE ELEMENT
c.moveToNext();
}
List myElements=new ArrayList();
游标c=db.query(…);
c、 moveToFirst();
而(c!=null&&!c.isAfterLast()){
添加(新元素(cursor.getString(0)…);
你肯定会有比赛条件-如果你对它很好,那么没有问题
How do I prevent that? Do I gain anything by threading this if the list I need to modify is synchronized?
我不这么认为
I mean, the threads will have to wait in line anyway, I might as well write the 4 queries and run them sequentially... or not?
The question is if I want to create 4 threads (each running in an AsyncTask) or just ONE AsyncTask that runs the 4 queries sequentially.
我将在一个AsyncTask中运行所有4个查询,创建4个AsyncTask将需要大量的工作和维护
你肯定会有比赛条件-如果你对它很好,那么没有问题
How do I prevent that? Do I gain anything by threading this if the list I need to modify is synchronized?
我不这么认为
I mean, the threads will have to wait in line anyway, I might as well write the 4 queries and run them sequentially... or not?
The question is if I want to create 4 threads (each running in an AsyncTask) or just ONE AsyncTask that runs the 4 queries sequentially.
我将在一个AsyncTask中运行所有4个查询,创建4个AsyncTask将需要大量的工作和维护。Vector
,与ArrayList
相反,它是同步的,线程安全的,因此我建议改用它。
另一种方法是为每个线程创建一个新的列表
,然后使用Collections.addAll()
将元素合并到原始列表中
要回答启动多个线程是否会有所收获的问题,答案可能取决于您执行的查询的成本。启动一个新线程具有内在的开销,因此您需要确保您启动的查询值得花费。Vector
,而不是ArrayList
,是同步的和线程安全的,因此我建议改用它。
另一种方法是为每个线程创建一个新的列表
,然后使用Collections.addAll()
将元素合并到原始列表中
要回答启动多个线程是否会有所收获的问题,答案可能取决于您执行的查询的成本。启动一个新线程会带来固有的开销,因此您需要确保您启动的查询值此成本。为什么需要运行简单的DB查询ly?下载我可以理解的文件需要单独处理,但我在UI线程上放置了相当复杂的DB查询,它们只需几秒钟即可返回。为什么需要异步运行简单的DB查询?下载我可以理解的文件需要单独处理,但我在UI线程上放置了相当复杂的DB查询它们只需要几秒钟就可以返回。