开发者

Android: Two or more threads? (Program is working)

I have created a sample/demo/test program in Android that runs quite nicely, if you see below you will see I have created a thread. Now I want to create another thread to work with another handler... since I cannot have two run() methods... how do I do this?

This is my (working - no errors) program:

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

        };



}


Use anonymous class like this.

    Thread thread2 = new Thread( new Runnable() {

        public void run() {
            // code here with your new handler
        }
    });


make two inner classes that extends Thread.

create an object for both the classes and call start on those objects.


You are suggesting that you want two runnables, yet you only have one runnable defined, which is your 'main' class. So what you need to do is make two different runnables, so that each can have their own code that can be run.

I would make two new classes, lets say, Runnable1 and Runnable2. I would have both of them implement the runnable interface. Each one of them can then contain different code to run in a separate thread.

Finally, I would change your thread creation/start code to look like this:

  Thread thread = new Thread(new Runnable1());
  Thread thread2 = new Thread(new Runnable2());
  thread.start();
  thread2.start();
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜