我有这个想法:
3个公共方法,2个命令和1个检查输入,并将在线程中启动command1或command2。我的问题是如何做到这一点?
public void blablabla() {
input = get_user_input;
if(input == 1) {
start thread with command1
} else {
start thread with command2
}
}
public void command1() {
// do action
}
public void command2() {
// do action2
}
我认为不可能直接用方法启动一个线程但是使用Runnable我可以做到这一点。我正在考虑它的良好选择和性能的好主意声明command1和command2在类上是静态可运行的,并使用此runnables来启动线程。这样做是静态可运行的,它会花费比方法更多的内存吗?
谢谢!
答案 0 :(得分:0)
您可以使用异步线程。试试下面这个例子
private class GetExampleDetails extends AsyncTask<String, Void, Void> {
private ProgressDialog dialog = new ProgressDialog(ExpensesListView.this);
String strMsg = null;
protected void onPreExecute() {
this.dialog.setMessage("Loading.....");
this.dialog.setCanceledOnTouchOutside(false);
this.dialog.show();
}
// automatically done on worker thread (separate from UI thread)
protected Void doInBackground(final String... a) {
try
{
//Write your code. which one do backround
}
catch(Exception ex)
{
ex.printStackTrace();
}
return null;
}
// can use UI thread here
protected void onPostExecute(final Void unused) {
if (this.dialog.isShowing()) {
this.dialog.dismiss();
this.dialog = null;
}
}
}//Endtask
检查一下。我认为这有助于你