java 多线程-线程的状态
作者:互联网
观察线程的状态
State state=Thread对象.getState();
int num=Thread.activeCount();//当前活跃的线程个数
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,Thread,int,activeCount,线程,多线程,public 来源: https://blog.51cto.com/14437184/2428929