I'm trying to create a new thread in the onCreate() of an activity, but instead of creating a new thread and executing the runnable's code in it, the runnable code is executing in the main thread of my program. A new thread never seems to be created.
The onCreate() code:
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.monster_layout);
runningMonsterViewActivity = this;
Thread.currentThread().setName("Main Thread");
Log.v(TAG, "onCreate() has run");
Thread genThread = new Thread(new TestRunnable());
genThread.run();
}
The runnable code:
import android.os.Handler;
import android.util.Log;
public class TestRunnable implements Runnable{
String TAG = "TestRunnable";
public TestRunnable()
{
// mainThreadHandler = h;
}
@Override
public void run() {
for(int i=0; i < 1000; i++){
Log.v(TAG, new Integer(i).toString());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
The stack trace I got when I paused the code when it was executing:
DalvikVM[localhost:8621] (Suspended)
Thread [<1> Main Thread] (Suspended)
VMThread.sleep(long, int) line: not available [native method]
Thread.sleep(long, int) line: 1306
Thread.sleep(long) line: 1286
TestRunnable.run() line: 18
Thread.run() line: 1096
MonsterViewActivity.onCreate(Bundle) line: 49
Instrumentation.callActivityOnCreate(Activity, Bundle) line: 1047
ActivityThread.performLaunchActivity(ActivityThread$ActivityRecord, Intent) line: 2627
ActivityThread.handleLaunchActivity(ActivityThread$ActivityRecord, Intent) line: 2679
ActivityThread.access$2300(ActivityThread, ActivityThread$ActivityRecord, Intent) line: 125
ActivityThread$H.handleMessage(Message) line: 2033
ActivityThread$H(Handler).dispatchMessage(Message) line: 99
Looper.loop() line: 123
ActivityThread.main(String[]) line: 4627
Method.invokeNative(Object, Object[], Class, Class[], Class, int, boolean) line: not available [native method]
Method.invoke(Object, Object...) line: 521
ZygoteInit$MethodAndArgsCaller.run() line: 868
ZygoteInit.main(String[]) line: 626
NativeStart.main(String[]) line: not available [native method]
Thread [<6> Binder Thread #2] (Suspended)
Thread [<5> Binder Thread #1] (Suspended)
Daemon System Thread [<3> Signal Catcher] (Suspended)
Daemon System Thread [<2> HeapWorker] (Suspended)
You just need to change genThread.run();
to genThread.start();
Right now, your code calls the run()
method from the main thread. start()
will actually start a new thread and will execute the run()
method on that thread , which is the desired behaviour.
You can simply use this snippet.
new Thread(new Runnable()
{
@Override
public void run()
{
//background task?
}
}).start();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.