本篇文章主要探索線程的各種運行狀態,包括new, runnable,block, native, terminate等。
1. New狀態下的線程
public void newThread(){
Thread th = new Thread();
Log.i("xxx","thread state:"+th.getState());
}
02-01 04:18:52.52022085-22085/xx.threadtest I/linhui: thread state:NEW
2. Runnable以及Native狀態下的線程
public void newThread(){
Thread th = new Thread("tiny"){
public void run(){
for(int i=0; i<Integer.MAX_VALUE; i++){
System. out.println(i);
}
}
};
th.start();
Log.i("linhui","thread state:"+th.getState());
}
02-01 04:37:15.21223132-23132/xxx.threadtest I/xxx: thread state:RUNNABLE
root@kylin32:/data/anr # top -t|grep 23632
23632 23671 0 25% R 923188K 98928K fg u0_a61 tiny xxx.threadtest
線程調用棧
3. Block狀態下的thread
public void newThread(){
final Object lock = new Object();
Runnable run = new Runnable() {
@Override
public void run() {
for(int i=0; i<Integer.MAX_VALUE; i++){
synchronized (lock) {
System. out.println(i);
}
}
}
};
Thread t1 = new Thread(run,"tiny1");
Thread t2 = new Thread(run,"tiny2");
t1.start();
t2.start();
Log.i("xxx","thread1 state:"+t1.getState());
Log.i("xxx","thread2 state:"+t2.getState());
}
24321 24370 1 16% R 925288K 98056K fg u0_a61 tiny1 xxx.threadtest
24321 24371 2 16% S 925288K 98056K fg u0_a61 tiny2 xxx.threadtest
tiny1處於runnable狀態
tiny2處於block狀態,正在等待進入object鎖
4. Waiting狀態下的線程
public void newThread(){
final Object lock = new Object();
Thread t1 = new Thread("tiny1"){
@Override
public void run() {
int i = 0;
while(true ){
synchronized (lock) {
try {
lock.wait();
} catch (InterruptedException e) {
}
System. out.println(i++);
}
}
}
};
Thread t2 = new Thread("tiny2"){
@Override
public void run() {
while(true ){
synchronized (lock) {
for(int i = 0; i< 10000000; i++){
System. out.println(i);
}
lock.notifyAll();
}
}
}
};
t1.start();
t2.start();
}
tiny2處於Runnable狀態:
tiny1處於Waiting狀態:
5. 線程Terminated狀態
public void newThread(){
Thread th = new Thread();
th.start();
try {
Log.i("xxx","thread state:"+th.getState());
th.sleep(2000);
}catch (InterruptedException e){
e.printStackTrace();
}
Log.i("xxx","thread final state:"+th.getState());
}
02-01 06:06:08.311 27270-27270/linhui.threadtestI/linhui: thread state:RUNNABLE
02-01 06:06:10.31127270-27270/linhui.threadtest I/linhui: thread final state:TERMINATED