线程阻止我的Android UI

时间:2011-06-02 19:49:20

标签: java android multithreading class nested

我的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!!" );
            }

        }

    }

}

这就是我运行它的方式:

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



    }
}
你可以帮帮我吗?我真的被卡住了;)

3 个答案:

答案 0 :(得分:6)

  

我的嵌套线程会阻止我的用户界面

您需要使用.start()代替.run()。也就是说,替换

Nested.run();

Nested.start();

run只是一种普通的方法。start()是实际产生新线程的方法,后者又运行run

答案 1 :(得分:0)

此代码存在问题:

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

繁忙的等待会占用CPU。

答案 2 :(得分:0)

package com.knobik.gadu;

import android.util.Log;

public class MyClass {

    public void StartTheThread() {
        Thread Nested = new Thread( new NestedThread() );
        Nested.run(); // Change this to Nested.start();
    }

    private class NestedThread implements Runnable {

        public void run() {

            while (true) { // infinite loop logical error
                Log.d( "DUPA!", "debug log SPAM!!" );
            }
        }
    }
}