开发者

Thread blocks my Android UI

I have a problem with java Threads in my Android app. My nested thread blocks my UI, how can i resolve this?

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

        }

    }

}

and this is how i run it:

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



    }
}

Could you help me? I'm literaly stuck ;)


My nested thread blocks my UI

You need to use .start() instead of .run(). That is, replace

Nested.run();

with

Nested.start();

(run is just an ordinary method. start() is the method that actually spawns a new thread, which in turn runs run)


This code is a problem:

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

A busy wait hogs the CPU.


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜