Android:新主题Runnable在主线程中执行

我正在尝试在一个activity的onCreate()中创build一个新的线程,但不是创build一个新的线程并在其中执行runnable的代码,而是在我的程序的主线程中执行可运行的代码。 一个新的线程似乎从未被创build。

onCreate()代码:

@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(); } 

可运行的代码:

 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(); } } } } 

我在执行代码时暂停了代码的堆栈跟踪:

 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) 

Solutions Collecting From Web of "Android:新主题Runnable在主线程中执行"

你只需要改变genThread.run(); genThread.start();

现在,你的代码从主线程调用run()方法。 start()实际上会启动一个新的线程,并在该线程上执行run()方法,这是所需的行为。

你可以简单地使用这个片段。

 new Thread(new Runnable() { @Override public void run() { //background task? } }).start();