gpt4 book ai didi

java - Android Studio,java公共(public)类中的线程

转载 作者:行者123 更新时间:2023-12-01 10:13:19 25 4
gpt4 key购买 nike

我创建了一个学生类,它调用一个需要用学生填充链接列表的线程。

class Students{
private LinkedList<Student> students = new LinkedList<Student>();
android.os.Handler handler = new android.os.Handler();

public String Fill() throws MalformedURLException {

String msg = "++";
new Thread(){
public void run(){
HttpURLConnection htcon=null;
try {
URL my_url = new URL("http://www.whatever.net/fill.php");
htcon = (HttpURLConnection) my_url.openConnection();
htcon.setDoOutput(true);
htcon.setUseCaches(false);

htcon.connect();
int responseCode = htcon.getResponseCode();
if(responseCode ==HttpURLConnection.HTTP_OK){
InputStream stream = htcon.getInputStream();
BufferedReader bfr = new BufferedReader(new InputStreamReader(stream,"UTF-8"));
String line = "";
StringBuilder strbld = new StringBuilder();
while ((line = bfr.readLine()) != null) {
strbld.append(line);
}
if (bfr!=null)
{
bfr.close();
}
String[] ary = strbld.toString().split("\n");
for (int i = 0; i < ary.length; i++) {
final Student temp = new Student(ary[i].toString().split(":")[0], "1210",Integer.parseInt(ary[i].toString().split(":")[1]), 0);

handler.post(new Runnable() {
@Override
public void run() {
students.push(new Student("jjj","k",9,9));
}
});
}//for
if (htcon!=null)
htcon.disconnect();
}

} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
}
}
}

}.start();
return toBinaryString(students.size());
}

问题是,当处理程序运行时,它不会更改列表。大小仍然是 0

这是我的 UI 类的样子(主要 Activity )

TextView txtv = (TextView) findViewById(R.id.textv);
Students students1 = new Students();
try {
msg = students1.Fill();
} catch (MalformedURLException e) {
e.printStackTrace();
Toast.makeText(this, e.toString(), Toast.LENGTH_LONG);
}

最佳答案

您的线程正在异步运行。所以,它会立即执行:

return toBinaryString(students.size());

当线程仍在进行中时。 AsyncTask确实足以解决你的问题。希望对您有所帮助。

关于java - Android Studio,java公共(public)类中的线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36039542/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com