简单例子用于查看线程的状态
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
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
相关文章推荐
- c#中子线程控制进度条的一个简单例子
- c#中子线程控制进度条的一个简单例子
- 一个简单的C#多线程间同步的例子
- 一个简单的C#多线程间同步的例子
- 一个简单的C#多线程间同步的例子
- 注入远程线程简单例子[修改]
- 一个简单的C#多线程间同步的例子
- 一个简单的C#多线程间同步的例子
- 一个简单的C#多线程间同步的例子
- 一个简单的C#多线程间同步的例子
- c#中子线程控制进度条的一个简单例子
- c#中子线程控制进度条的一个简单例子 - jinjazz - CSDNBlog
- C#中子线程控制进度条的一个简单例子
- vb2005 创建和使用线程的简单例子
- c#中子线程控制进度条的一个简单例子
- c#中子线程控制进度条的一个简单例子
- c#中子线程控制进度条的一个简单例子
- Linux下C语言实现的简单使用线程向FIFO里写入与读取数据的例子
- 一个简单的C#多线程间同步的例子
- [C#] 一个简单的C#多线程间同步的例子