一个线程一般会分为这么几个状态
1, NEW
Thread.start();
2, RUNNABLE
就绪状态和运行状态
3,BLOCKED
wait,io操作 read和write;
4,WAITING
sleep,join
5,TIMED_WAITING
sleep,join
6,TERMINATED
死亡状态
package y.i.d;
import java.lang.Thread.State;
public class AllState {
public static void main(String[] args) {
Thread t=new Thread(()-> {
for (int i = 0; i < 5;i++) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
State state = t.getState();
System.out.println(state); // NEW
t.start();
state = t.getState();
System.out.println(state); // RUNNABLE
while(state != Thread.State.TERMINATED) {
try {
Thread.sleep(100);
state = t.getState(); // TIMED_WAITING or RUNNABLE
System.out.println(state);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
state = t.getState(); // TERMINATED
System.out.println(state);
}
}
也可以使用线程数来控制
package y.i.d;
import java.lang.Thread.State;
public class AllState {
public static void main(String[] args) {
Thread t=new Thread(()-> {
for (int i = 0; i < 5;i++) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
State state = t.getState();
System.out.println(state); // NEW
t.start();
state = t.getState();
System.out.println(state); // RUNNABLE
while(true) {
int count =Thread.activeCount();
if(count==1) {
System.out.println(count);
break;
}
try {
Thread.sleep(100);
System.out.println(count);
state = t.getState(); // TIMED_WAITING or RUNNABLE
System.out.println(state);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}