线程阻止我的Android UI

Kno*_*bik 1 java multithreading android nested class

我的Android应用程序中的java Threads有问题.我的嵌套线程阻止了我的UI,我该如何解决这个问题呢?

MyClass.java

package com.knobik.gadu;

import android.util.Log;

public class MyClass {

    public void StartTheThread() {

        Thread Nested = new Thread( new NestedThread() );
        Nested.run();
    }

    private class NestedThread implements Runnable {

        public void run() {

            while (true) {
                Log.d( "DUPA!", "debug log SPAM!!" );
            }

        }

    }

}
Run Code Online (Sandbox Code Playgroud)

这就是我运行它的方式:

package com.knobik.gadu;

import java.io.IOException;

import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

public class AndroidGadu extends Activity {
    public static final String LogAct = "AndroidGadu";

    public void OnClickTest(View v) {

        MyClass test = new MyClass();
        test.StartTheThread();

    }


    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);



    }
}
Run Code Online (Sandbox Code Playgroud)

你可以帮帮我吗?我文字卡住;)

aio*_*obe 6

我的嵌套线程阻止了我的UI

你需要使用.start()而不是.run().也就是说,替换

Nested.run();
Run Code Online (Sandbox Code Playgroud)

Nested.start();
Run Code Online (Sandbox Code Playgroud)

(run这只是一个普通的方法.start()实际上生成一个新线程的方法,然后运行run)

  • +1,我看到很多人在他们的`Thread`对象上调用`run()`而不是`start()`.:( (2认同)