http://blog.csdn.net/libaineu2004/article/details/25692655
文章来源:http://my.oschina.net/ldaga/blog/65213
http://blog.csdn.net/jspamd/article/details/5262894
网上说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 | }; |
1 | new Thread(sendable).start(); |