【Java开源代码栏目提醒】:网学会员鉴于大家对Java开源代码十分关注,论文会员在此为大家搜集整理了“TextSleepAndInterrupt.java”一文,供大家参考学习
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(); //调用方法判断是否唤醒
}
}