您的位置:首页 > 其它

简单例子用于查看线程的状态

2014-11-24 11:41 218 查看
线程简单的测试例子,用于了解线程的概念和状态

public class ThreadState implements Runnable {

public synchronized void waitForASecond() throws InterruptedException{
wait(500);
System.out.println("我在等待5毫秒");
}
public synchronized void waitForYears() throws InterruptedException{
wait();
System.out.println("我在永久等待");
}

public synchronized void notifyNow(){
notify();
System.out.println("我被唤醒了");
}
public void run() {
try {
waitForASecond();
} catch (InterruptedException e) {
e.printStackTrace();
}
try {
waitForYears();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

public class Test {

public static void main(String[] args) throws InterruptedException {
ThreadState state = new ThreadState();
Thread thread =  new Thread(state);
System.out.println("新建线程"+thread.getState());
thread.start();
System.out.println("启动线程"+thread.getState());
thread.sleep(100);
System.out.println("计时等待"+thread.getState());
thread.sleep(1000);
System.out.println("等待线程"+thread.getState());
state.notifyNow();
System.out.println("唤醒线程"+thread.getState());
thread.sleep(1000);
System.out.println("终止线程"+thread.getState());
}

}

输出:

新建线程NEW

启动线程RUNNABLE

计时等待TIMED_WAITING

我在等待5毫秒

等待线程WAITING

我被唤醒了

我在永久等待

唤醒线程TERMINATED

终止线程TERMINATED
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: