1.创建Android线程
参考官方文档是个好习惯。
http://developer.android.com/reference/java/lang/Thread.html
http://developer.android.com/guide/components/processes-and-threads.html
创建线程有两种方式:一是在创建线程的时候传入一个Runnable对象,另一种是继承Thread类,实现run()方法。这两种方法没啥区别嘛。。。
Game start....
(1)用Runnable对象
源码MainActivity.java
package com.example.siqi;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/**
* 线程1
*/
new Thread(new Runnable(){
@Override
public void run() {
int cnt = 10;
while(cnt>0) {
Log.d("Thread1", "Thread one cnt: " + cnt--);
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
break;
}
}
}
}).start();
/**
* 线程2
*/
new Thread(new Runnable(){
@Override
public void run() {
int cnt = 10;
while(cnt>0) {
Log.d("Thread2", "Thread two cnt: " + cnt--);
try {
Thread.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
break;
}
}
}
}).start();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
结果:
11-07 16:30:07.844: D/Thread1(13237): Thread one cnt: 10
11-07 16:30:07.873: D/Thread2(13237): Thread two cnt: 10
11-07 16:30:08.043: D/Thread1(13237): Thread one cnt: 9
11-07 16:30:08.173: D/Thread2(13237): Thread two cnt: 9
11-07 16:30:08.244: D/Thread1(13237): Thread one cnt: 8
11-07 16:30:08.443: D/Thread1(13237): Thread one cnt: 7
11-07 16:30:08.483: D/Thread2(13237): Thread two cnt: 8
11-07 16:30:08.680: D/Thread1(13237): Thread one cnt: 6
11-07 16:30:08.818: D/Thread2(13237): Thread two cnt: 7
11-07 16:30:08.887: D/Thread1(13237): Thread one cnt: 5
11-07 16:30:09.095: D/Thread1(13237): Thread one cnt: 4
11-07 16:30:09.164: D