我试图从请求函数中获取一个String并将其添加到lastList ArrayList中,但不会正常添加。
在这种情况下,如何添加?
作为全局变量public ArrayList lastList = new ArrayList <>();但这没用。
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
Log.d(MainActivity.TAG, "Task runned.");
for (int i = 0; i < alarmList.size(); i++) {
final String str[] = alarmList.get(i).split("#!%~#");
for (int j = 0; j <= 8; j++) {
try {
final String output = AddActivity.request(str[1], str[2]);
handler.post(new Runnable() {
public void run() {
if (Integer.parseInt(str[3]) == Integer.parseInt(StringUtils.substringBetween(output, str[1] + " ", "화"))) {
lastList.add(output);
}
}
});
Log.d(MainActivity.TAG, "OK");
break;
} catch (Exception ex) {
Log.d(MainActivity.TAG, "Exception.");
}
}
}
}
});
thread.start();
try {
thread.join();
Log.d(MainActivity.TAG, "thread end.");
Log.d(MainActivity.TAG, "Size: " + lastList.size()); // Size: 0
}
我希望输出Size:1,但实际输出是Size:0。
答案 0 :(得分:0)
问题在于:
handler.post(new Runnable() {
使您的:
lastList.add(output);
在登录后执行:
Log.d(MainActivity.TAG, "Size: " + lastList.size()); // Size: 0
从代码中尚不清楚为什么需要使用handler.post
,这在需要从工作线程更新UI小部件时经常使用。
答案 1 :(得分:0)
不确定代码中的handler
是什么,但似乎它使http POST,然后在POST响应后在另一个线程中执行回调。因此,据我了解,您正在线程thread
上加入连接,但是您正在另一个线程中更新列表,该线程在POST回调中执行。由于http调用通常需要更长的时间才能执行几行代码,因此您看不到列表已更新。可以确定-尝试将Tread.sleep(10000)
放在thread.join()
之后;并检查大小是否为1。此外,在此处放置一些调试日志语句将非常有帮助,在此lastList.add(output)
之后放置一些日志行,以便可以看到执行顺序。
然后,您也可以通过在回调线程上加入join来修复它。
只是为了说明我提出了以下测试代码的想法:
static Thread innerThread;
static ArrayList lastList = new ArrayList<>();
public static void main(String[] args) {
System.out.println("Thread main: started.");
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("Thread thread: started.");
innerThread = new Thread(new Runnable() {
public void run() {
System.out.println("Thread innerThread: started.");
try {
System.out.println("Thread innerThread: sleeping for 1 second.");
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
lastList.add("test");
System.out.println("Thread innerThread: value added to the lastList");
System.out.println("Thread innerThread: ended.");
}
});
innerThread.start();
System.out.println("Thread thread: ended.");
}
});
thread.start();
try {
thread.join(); // to be sure that thread is finished - innerTread is initialized
innerThread.join(); // to be sure that innerTread is finished - lastList is updated
System.out.println("Thread main: lastList.size() = " + lastList.size()); // Size: 1
} catch (Exception e){
e.printStackTrace();
}
System.out.println("Thread main: ended.");
}
输出:
Thread main: started.
Thread thread: started.
Thread thread: ended.
Thread innerThread: started.
Thread innerThread: sleeping for 1 second.
Thread innerThread: value added to the lastList
Thread innerThread: ended.
Thread main: lastList.size() = 1
Thread main: ended.
希望这会有所帮助!