启动和停止线程的正确方法是什么

时间:2014-07-03 13:44:03

标签: android multithreading

我需要写下面的内容。单击按钮时,应启动新线程。 Run方法是无限循环,它在TextView中为instanse文本更改,当我再次按下按钮时,它应该停止更改文本。 如果没有危险的方法,请以正确的方式帮助您完成此操作。 Thx提前。

2 个答案:

答案 0 :(得分:2)

private Thread t;
private String threadName;
private boolean suspended = false;

public void run() {
    System.out.println("Running " +  threadName );

    try {
        for(int i = 10; i > 0; i--) {
            System.out.println("Thread: " + threadName + ", " + i);
            // Let the thread sleep for a while.
            Thread.sleep(300);
            synchronized(this) {
                while(suspended) {
                    wait();
                }
            }
        }
    } catch (InterruptedException e) {
        System.out.println("Thread " +  threadName + " interrupted.");
    }

    System.out.println("Thread " +  threadName + " exiting.");
}

public void start () {
    System.out.println("Starting " +  threadName );
    if (t == null) {
        t = new Thread (this, threadName);
        t.start ();
    }
}

void suspend() {
    suspended = true;
}

synchronized void resume() {
    suspended = false;
    notify();
}

答案 1 :(得分:0)

我不清楚你想为我做什么。

但我敢打赌,你可以使用带有doInBackground和onProgressUpdate的AsyncTask进行操作,看看。

相关问题