文章出自:http://blog.csdn.net/cuiran/article/details/6133745
线程的休眠状态和就绪(包括等待)状态的不同之处在于,处于休眠状态的线程并不释放运行资源,在休眠结束后。不用等待被JVM线程调度器再度选中,而可以直接进入运行状态。
结束休眠状态有两种途径:
①休眠时间到达后,线程重新进入运行状态。
②处于休眠状态的线程遇上java.lang.InterruptedException异常,从而被迫停止休眠。
使线程进入休眠状态可以直接调用Thread.sleep();打断某线程的休眠状态的手段是调用该线程的interrupt()方法。
下面通过例子来说明。在例子中开启一个子线程thread1,该子线程开始休眠5分钟,在此期间主线程调用thread1对象的interrupt()方法中断其休眠。
- /**
- * InterruptSleepingThread.java
- * 版权所有(C) 2011 cuiran2001@163.com
- * 创建:崔冉 2011-1-11 下午02:57:20
- */
- package com.cayden.thread7233;
- /**
- * @author 崔冉
- * @version 1.0.0
- * @desc
- */
- public class InterruptSleepingThread {
- /**
- * @param args
- */
- public static void main(String[] args) throws InterruptedException{
- // TODO Auto-generated method stub
- WaitingThread thread1=new WaitingThread();
- thread1.start();
- Thread.sleep(5000);
- synchronized(thread1)
- {
- thread1.interrupt();
- }
- }
- }
- class WaitingThread extends Thread
- {
- public void run(){
- System.out.println("线程开始休眠5分钟");
- try{
- Thread.sleep(5*60*1000);
- }catch (InterruptedException e) {
- // TODO: handle exception
- System.out.println("线程被中断休眠");
- }
- System.out.println("线程结束休眠");
- }
- }
运行效果如下:
- 线程开始休眠5分钟
- 线程被中断休眠
- 线程结束休眠
中断某线程的休眠状态代码需要放在锁定线程对象的同步锁中。
代码中:
synchronized(thread1)
{
thread1.interrupt();
}