我想用线程编写代码来创建并发应用程序。 当我点击“主线程”按钮时,“doHeavyWork”方法启动并在用户完成时向用户显示祝酒!
但是当我想使用线程并单击“单线程”按钮时,“doHeavyWork”方法启动,但最后程序停止并崩溃。
我的问题是什么?
我使用物理手机进行调试。
这些是我的代码:
package khosravi.mehdi.course.app.thread_test;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Toast;
public class MyTestThreadActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
findViewById(R.id.btnMainThread).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
doHeavyWork();
}
});
findViewById(R.id.btnSingleThread).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
doHeavyWork();
}
});
thread.start();
}
});
}
public void doHeavyWork() {
String str = "";
for (int i = 0; i < 7000; i++) {
str += i;
Log.i("LOG", "i:" + i);
}
Toast.makeText(MyTestThreadActivity.this, "Heavy Work is finish !", Toast.LENGTH_SHORT).show();
}
}
答案 0 :(得分:0)
在您的活动中尝试使用此代码,以便在UI线程上运行与显示相关的内容。
Request started: "POST" http://localhost:9090/signalr/abort?transport=webSockets...
Request ended: http://localhost:9090/signalr/connect?transport=webSockets... with HTTP status 101.0
Request ended: http://localhost:9090/signalr/abort?transport=webSockets&clientProtocol=1.4.... with HTTP status 200.0
WriteCompletedInline
Action = 00000002
Action = 00000000
Request ended: http://localhost:9090/signalr/connect?transport=webSockets.... with HTTP status 101.0
Request ended: http://localhost:9090/BotDetectCaptcha.ashx?get=image&c=SampleCaptcha&t=44c45e60afac46809bfce16e123b54a2 with HTTP status 200.0