Java开发实战1200例(I)-----124查看线程的运行状态
package Test123;
//测试代码
public class Test {
public static void main(String[] args)throws InterruptedException{
ThreadState state=new ThreadState();
Thread thread=new Thread(state);
//有new操作符为新建状态
System.out.println("新建线程:" + thread.getState());
thread.start();
//start为线程启动状态
System.out.println("启动线程:" + thread.getState());
Thread.sleep(100);
//wait(100)计时等待状态,括号内为计时时间
System.out.println("计时等待:" + thread.getState());
Thread.sleep(1000);
//wait()括号内没有时间,为永久等待状态
System.out.println("等待线程:" + thread.getState());
state.notifyNow();
//notify()为唤醒wait()挂起的线程
System.out.println("唤醒线程:" + thread.getState());
Thread.sleep(1000);
System.out.println("终止线程:" + thread.getState());
}
}
package Test123;
public class ThreadState implements Runnable {
public synchronized void waitForASecond()throws InterruptedException{
wait(500);
}
public synchronized void waitForYears() throws InterruptedException{
wait();
}
public synchronized void notifyNow() throws InterruptedException{
notify();
}
@Override
public void run() {
// TODO Auto-generated method stub
try {
waitForASecond();
waitForYears();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
注:测试部分为Thread类的基本方法Thread.start();notify();wait(),run()等,还有很多方法请自行查找!
下附内容状态图谱