标签:java 活跃 tar gets thread bre trace 观察 for
观察线程的状态public class n {
public static void main(String[]args) throws InterruptedException
{
Thread t =new Thread(()->{
for(int i=0;i<5;i++)
{
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("a");
}
});
//观察状态
State state=t.getState();
System.out.println(state);//创建的对象处于NEW新生状态
t.start();
state=t.getState();
System.out.println(state);//处于RUNNABLE
while(state!=Thread.State.TERMINATED)
{
System.out.println(num);
Thread.sleep(200);
state =t.getState();//TIMED_WAITING
System.out.println(state);
}
**或者:**
while(true)
{
int num=Thread.activeCount();//当前活动的线程数,包括主线程一共有两个
if(num==1)
{
break;
}
System.out.println(num);
Thread.sleep(200);
state=t.getState();
System.out.println(state);
}
state=t.getState();
System.out.println(state);//TERMINATED
}
}
标签:java 活跃 tar gets thread bre trace 观察 for
原文地址:https://blog.51cto.com/14437184/2428929