我们都知道,在主线程主要完成UI绘制和相应用户操作,而在子线程里面完成耗时的任务,当我们需要在子线程里面更新UI时,怎么办呢,这时就需要用到runOnUiThread()这个方法。不多说,贴上我大学时参加互联网+(校园食尚app)里的部分代码。
private void work(){
new Thread(new Runnable() {
@Override
public void run() {
Connection connection=JDBCOperation.getConn();
String sql="select * from food";
PreparedStatement preparedStatement;
try {
preparedStatement=(PreparedStatement)connection.prepareStatement(sql);
ResultSet resultSet=preparedStatement.executeQuery();
while (resultSet.next()){
Food food=new Food(resultSet.getString("Name"),resultSet.getInt("Imageid"),resultSet.getString("Address"),resultSet.getDouble("Price"),resultSet.getDouble("Hot"),resultSet.getString("Evaluate"),resultSet.getInt("Number"));
foodList.add(food);
}
show();
} catch (SQLException e) {
e.printStackTrace();
}
}
}).start();
}
private void show(){
runOnUiThread(new Runnable() {
@Override
public void run() {
RecyclerView recyclerView= (RecyclerView) findViewById(R.id.recycler_view);
LinearLayoutManager linearLayoutManager=new LinearLayoutManager(AllDishes.this);
recyclerView.setLayoutManager(linearLayoutManager);
FoodAdapter adapter=new FoodAdapter(foodList,R.layout.food_item1);
recyclerView.setAdapter(adapter);
}
});
}
在这上面,通过子线程从阿里云里获取食物表里面的数据,之后把它们加到元素为Food这个类的动态数组Arraylist里面。这时我需要对现在的UI进行更新,那么就调用runOnUiThread()方法,使run()里面的代码在主线程中运行。此时我的更新的操作是用recyclerView滑动显示某类菜品的信息。