// Java 程序 - 演示线程状态classthreadimplementsRunnable{publicvoidrun(){// thread2 - 超时等待try{Thread.sleep(1500);
}catch(InterruptedExceptione){e.printStackTrace();
}System.out.println("State of thread1 while it called join() method on thread2 -"+
Test.thread1.getState());
try{Thread.sleep(200);
}catch(InterruptedExceptione){e.printStackTrace();
}}}publicclassTestimplementsRunnable{publicstaticThreadthread1;
publicstaticTestobj;
publicstaticvoidmain(String[]args){obj = newTest();
thread1 = newThread(obj);
// 创建 thread1,现在是初始状态System.out.println("State of thread1 after creating it - " + thread1.getState());
thread1.start();
// thread1 - 就绪状态System.out.println("State of thread1 after calling .start() method on it - " +
thread1.getState());
}publicvoidrun(){threadmyThread = newthread();
Threadthread2 = newThread(myThread);
// 创建 thread1,现在是初始状态System.out.println("State of thread2 after creating it - "+ thread2.getState());
thread2.start();
// thread2 - 就绪状态System.out.println("State of thread2 after calling .start() method on it - " +
thread2.getState());
// moving thread1 to timed waiting state try{//moving - 超时等待Thread.sleep(200);
}catch(InterruptedExceptione){e.printStackTrace();
}System.out.println("State of thread2 after calling .sleep() method on it - "+
thread2.getState());
try{// 等待 thread2 终止thread2.join();
}catch(InterruptedExceptione){e.printStackTrace();
}System.out.println("State of thread2 when it has finished it's execution - " +
thread2.getState());
}}
以上代码运行输出结果为:
State of thread1 after creating it - NEW
State of thread1 after calling .start() method on it - RUNNABLE
State of thread2 after creating it - NEW
State of thread2 after calling .start() method on it - RUNNABLE
State of thread2 after calling .sleep() method on it - TIMED_WAITING
State of thread1 while it called join() method on thread2 -WAITING
State of thread2 when it has finished it's execution - TERMINATED