本篇文章主要探索线程的各种运行状态,包括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