Android:两个或更多线程?(程序正在运行)

Rya*_*yan 0 multithreading android


我在Android中创建了一个样本/演示/测试程序,运行得非常好,如果你看到下面你会看到我创建了一个线程.现在我想创建另一个线程来处理另一个处理程序...因为我不能有两个run()方法...我该怎么做?

这是我的(工作 - 没有错误)计划:

package com.ryan1;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.TextView;

public class main extends Activity implements Runnable{

int level = 0;
int seconds_running=0;

TextView the_seconds,the_level;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    the_seconds = (TextView) findViewById(R.id.textview_seconds);
    the_level = (TextView) findViewById(R.id.textview_level);

        Thread thread = new Thread(this);
        Thread thread2 = new Thread(this);
        thread.start();
        thread2.start();
}

public void run() {

    while(seconds_running<500)
    {
        if(seconds_running %5 ==0){level++;}     

             try {
                 handler.sendEmptyMessage(0);
                 int a = 1000 - (level*100);
                 if(a<=100){a=25;}
                Thread.sleep(a);
                System.out.println("R "+Thread.currentThread());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
    }

        }



private Handler handler = new Handler() {

                @Override

                public void handleMessage(Message msg) {

                    seconds_running++;
                    int a = 1000 - (level*100);
                    the_seconds.setText(" "+seconds_running);
                    the_level.setText(level+" "+a);
                }

        };



}
Run Code Online (Sandbox Code Playgroud)

Pri*_*ley 5

像这样使用匿名类.

    Thread thread2 = new Thread( new Runnable() {

        public void run() {
            // code here with your new handler
        }
    });
Run Code Online (Sandbox Code Playgroud)