2011-06-02 68 views
1

我的Android應用程序中的Java線程有問題。我的嵌套線程阻止我的用戶界面,我該如何解決這個問題?線程塊我的Android 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); 



    } 
} 

你能幫助我嗎?我literaly卡;)

回答

6

我嵌套線程塊我的UI

您需要使用.start()而不是.run()。也就是說,更換

Nested.run(); 

Nested.start(); 

run只是一個普通的方法。start()是實際產生一個新的線程,這反過來又運行run方法)

+2

+1,我看到很多人在'Thread'對象上調用'run()'而不是'start()'。 ( – mre 2011-06-02 19:54:08

+0

我也是。標準錯誤真的。 – aioobe 2011-06-02 19:54:49

+0

好吧,我的java expiriance是2天長。謝謝你的回答。如果這有助於我的錯誤發佈:) – Knobik 2011-06-02 20:03:38

0

此代碼是一個問題:

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

一個忙等待CPU。

+0

不是一個真正的體面的操作系統會傳播負載,真正的原因是不啓動線程 – 2011-06-02 19:55:33

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