我在Runner的主要活动中有两个线程,然后单击一个按钮启动它们。你唯一要做的就是数数。我想从ech线程更新当前计数的两个TextView。当我启动我的应用程序并单击我的按钮时,该应用程序崩溃了。
代码在控制台中正常运行。
类Runner仅用于计数。我想在方法running()的每一段之后更新两个TextView。
public class Runner extends Activity implements Runnable { int count = 0; String name; public Runner(String name) { super(); this.name = name; } public void warten() throws InterruptedException { int zahl = (int) (Math.random() * 500) + 500; Thread.sleep(zahl); } public void running() throws InterruptedException { for(int i = 0; i < 10; i++) { warten(); count++; System.out.println(name + " ist bei: " + count); if(count == 10) { System.out.println(name + " IST FERTIG"); } runOnUiThread(new UiThread(name, count)); } } public void run() { try { running(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
类UiThread应该是用于更新UI的主线程。
public class UiThread extends Activity implements Runnable {
String name;
int count;
TextView textView1;
TextView textView2;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
textView1 = findViewById(R.id.textView2);
textView2 = findViewById(R.id.textView3);
}
public UiThread(String name, int count){
this.name = name;
this.count = count;
}
@Override
public void run() {
if(name == "thread1"){
textView1.setText("thread1 ist bei: " + count);
}else{
textView2.setText("thread2 ist bei: " + count);
}
}
}
我在Runner的主要活动中有两个线程,然后单击一个按钮启动它们。你唯一要做的就是数数。我想从ech线程更新当前计数的两个TextView。当...