日期:2014-05-20  浏览次数:20777 次

线程睡眠唤醒问题,一直不明白,请给解释一下.程序来自:Java 案例大全
/* 1 getUp()里的这句, Thread.currentThread().interrupt(); 要把谁唤醒? 这个线程是谁?
  2 text.join(),这句要一直执行完,执行完后,这个线程结束了. 但怎么输出的结果"Thread-0 15-26-45:0570Thread-0 唤醒异常:sleep interrupted" 还有Thread-0呢?
 */

   
package com.zf.s14; //创建一个包
import java.text.DateFormat; //引入类
import java.text.SimpleDateFormat;
import java.util.Date;
public class TextSleepAndInterrupt extends Thread { // 操作线程沉睡与唤醒的类
private DateFormat dateFormat = new SimpleDateFormat("HH-mm-ss:SSSS");
public void run() {
System.out
.println(dateFormat.format(new Date()) + getName() + " 沉睡3秒钟");
try {
sleep(3000); // 线程休眠3秒
} catch (InterruptedException e) { // 捕获唤醒异常
System.out.println(getName() + dateFormat.format(new Date())
+ getName() + " 唤醒异常:" + e.getMessage());
}
System.out.print(dateFormat.format(new Date()) + " 沉睡期间是否唤醒?");
try {
sleep(2000); // 线程休眠2秒
} catch (InterruptedException e) { // 捕获唤醒异常
System.out.println(getName() + dateFormat.format(new Date())
+ getName() + " 唤醒异常:" + e.getMessage());
}
System.out.println(!isAlive()); // 线程是否激活,false表示不是激活的
interrupt();// 唤醒线程
System.out.print(dateFormat.format(new Date()) + " 沉睡的我,是否唤醒?");
System.out.println(isAlive()); // 线程是否激活
}
public void getUp(){
Thread.currentThread().interrupt(); // 唤醒当前线程
while (true) {
if (Thread.currentThread().isInterrupted()) { // 判断当前线程是否被唤醒
System.out.println(dateFormat.format(new Date())+" 当前我是否被唤醒 ?"
+ Thread.currentThread().isInterrupted());
try {
Thread.currentThread().sleep(2000); // 线程休眠2秒
} catch (InterruptedException e) { // 捕获唤醒异常
System.out.println(getName() + dateFormat.format(new Date())
+ getName() + " 唤醒异常:" + e.getMessage());
}
System.out.println(dateFormat.format(new Date())+" 沉睡后是否被唤醒?"
+ Thread.currentThread().isInterrupted());
}
}
}
public static void main(String[] args) { // java程序主入口处
TextSleepAndInterrupt text=new TextSleepAndInterrupt();//实例化对象
text.start(); //启动线程
try {
text.join(); //等待线程运行结束
} catch (InterruptedException e) { // 捕获唤醒异常
System.out.println(" 唤醒异常:" + e.getMessage());
}
text.getUp(); //调用方法判断是否唤醒
}
}
/* 这是运行输出结果

5-26-40:0569Thread-0 沉睡3秒钟
15-26-43:0570 沉睡期间是否唤醒?false
15-26-45:0570 沉睡的我,是否唤醒?true
15-26-45:0570 当前我是否被唤醒 ?true
Thread-015-26-45:0570Thread-0 唤醒异常:sleep interrupted
15-26-45:0570 沉睡后是否被唤醒?false
*/



------解决方案--------------------
Thread.currentThread().interrupt();是将当前线程中断,让出CPU.
------解决方案--------------------
LZ,这个不是唤醒,这个是线程中断,线程在sleep的时候是阻塞等待的,如果收到中断信号,就会在调用的方法(这里是sleep)上抛出InterruptedException异常,这个是中断线程。。

唤醒是 wait 和 notify 、 notifyAll,在线程wait在某的管程上时,可以有线程对此管程上的线程做notify或 notifyAll 操作,来唤醒wait在此管程上的线程
------解决方案--------------------
不是都说线程问题都在每个线程里建个print来看就可以了么.。喵.
------解决方案--------------------
LZ你不就只有一个线程么
------解决方案--------------------
TextSleepAndInterrupt text=new TextSleepAndInterrupt();//实例化对象
text.start(); //启动线程

System.out.println(dateFormat.format(new Date()) + getName() + " 沉睡3秒钟");
sleep(3000);
System.out.print(dateFormat.format(new Date()) + " 沉睡期间是否唤醒?");
sleep(2000);