jianglilili / jianglilili/guodegang.github.io
查看线程的运行状态
- Dominant language
- No language data
- Stars
- 0
- Forks
- 0
- PR merge metrics
- No merged PRs in 30d
Description
- 线程共有**新建**、**运行(可运行)**、**阻塞**、**等待**、**计时等待**和**终止**6种状态。当使用new操作符创建新线程时,线程处于新建状态。当调用start()方法时,线程处于运行(可运行)状态。当线程需要获得对象的内置锁,而该锁正被其他线程拥有时,线程处于阻塞状态。当线程等待其他线程通知调度表可以运行时,该线程处于等待状态。对于一些含有时间参数的方法,如Thread类的sleep()方法,可以使线程处于计时等待状态。当run()方法运行完毕或出现异常时,线程处于终止状态。
- 编写ThreadState类,该类实现了Runnable接口。在该类中定义了3个方法:waitForASecond()方法用于将当前线程暂时等待0.5秒,waitForYears()方法用于将当前线程永久等待,notifyNow()方法用于通知等待状态的线程运行。run()方法中,运行了waitForASecond()和waitForYears()方法。
```
public class ThreadState implements Runnable
{
public synchronized void waitForASecond() throws InterruptedException
{
wait(500); //使当前线程等待0.5秒或其他线程调用notify()或notifyAll()方法
}
public synchronized void waitForYears() throws InterruptedException
{
wait(); //使当前线程永久等待,直到其他线程调用notify()或notifyAll()方法
}
public synchronized void notifyNow() throws InterruptedException
{
notify(); //唤醒由调用wait()方法进入等待状态的线程
}
public void run()
{
try
{
waitForASecond(); //在新线程中运行waitForASecond()方法
waitForYears(); //在新线程中运行waitForYears()方法
}catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
```
- 编写ThreadStateTest类进行测试,在main()方法中输出了线程的各种不同状态
```
public class ThreadStateTest
{
public static void main(String[] args) throws InterruptedException
{
ThreadState state=new ThreadState(); //创建state对象
Thread thread=new Thread(state); //利用state对象创建Thread对象、
System.out.println("新建线程:"+thread.getState());//新建线程状态
thread.start(); //调用thread对象的start()方法,启动新线程
System.out.println("启动线程:"+thread.getState());//输出线程状态
Thread.sleep(100); //当前线程休眠0.1秒,使新线程运行waitForASecond()方法
System.out.println("计时等待:"+thread.getState());//输出线程状态
Thread.sleep(1000); //当前线程休眠1秒,使新线程运行waitForYears()方法
System.out.println("等待线程:"+thread.getState());//输出线程状态
state.notifyNow(); //调用state的notifyNow()方法
System.out.println("唤醒线程:"+thread.getState());//输出线程状态
Thread.sleep(1000); //当线程休眠1秒,使新线程结束
System.out.println("终止线程:"+thread.getState());//输出线程状态
}
}
```
Contributor guide
No contributing guide indexed for this repository
Assessment
This issue has not been assessed yet.