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

本文通过一个简单的线程测试例子,介绍了线程的概念、状态及其操作,包括等待、唤醒等关键过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

线程简单的测试例子,用于了解线程的概念和状态

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值