Android Thread第二次Thread.start()报错的疑问

网上说Thread不需要stop()的原因是因为运行到尾部就会自动释放,而代码:
01
Thread myThread = new Thread(new Runnable() {
02
 
03
    @Override
04
    public void run() {
05
        // TODO Auto-generated method stub
06
        Log.i("thread", "" + count);
07
        while (runable) {
08
            
09
                count++;
10
                try {
11
                    Thread.sleep(100);
12
                } catch (Exception e) {
13
                }
14
                Message msg = mhandler.obtainMessage(FLAG_UPDATE, 0, 0);
15
                mhandler.sendMessage(msg);
16
            }
17
        
18
    }
19
});
在第二次start()的时候,系统抛出异常:java.lang.IllegalThreadStateException: Thread already started.
这是个很悲催的事情,而我现在也只能,这样:
01
Thread myThread = new Thread(new Runnable() {
02
 
03
    @Override
04
    public void run() {
05
        // TODO Auto-generated method stub
06
        Log.i("thread", "" + count);
07
        while (true) {
08
            if (runable) {
09
                count++;
10
                try {
11
                    Thread.sleep(100);
12
                } catch (Exception e) {
13
                }
14
                Message msg = mhandler.obtainMessage(FLAG_UPDATE, 0, 0);
15
                mhandler.sendMessage(msg);
16
            }
17
        }
18
    }
19
});
        不过这样的牺牲就是有线程在无限循环...性能...
        不知列位大牛是怎么处理这里的。
 
这个已经解决了,可以写一个继承Thread的类,或者写一个Runnable,然后再new Thread(xx).start();就可以了,回头看一下,真小白啊!

新代码如下:
创建一个Runnable,用于Thread执行

1
Runnable sendable = new Runnable() {
2
 
3
    @Override
4
    public void run() {
5
        // TODO Auto-generated method stub
6
 
7
    }
8
};
run方法中写上需要操作的逻辑,然后这样调用:


1
new Thread(sendable).start();
这样,每次需要调用的时候会重新new一个Thread,大体是这样,但可以无限次数运行。

 

 

转:http://my.oschina.net/ldaga/blog/65213

posted on 2013-03-08 13:59  jiezzy  阅读(3295)  评论(0编辑  收藏  举报