public class SleepInterrupt extends Object implements Runnable{
public void run(){
try{
System.out.println("in run() - about to sleep for 20 seconds");
Thread.sleep(20000);
System.out.println("in run() - woke up");
}catch(InterruptedException e){
System.out.println("in run() - interrupted while sleeping");
//处理完中断异常后,返回到run()方法人口,
//如果没有return,线程不会实际被中断,它会继续打印下面的信息
return;
}
System.out.println("in run() - leaving normally");
}
public static void main(String[] args) {
SleepInterrupt si = new SleepInterrupt();
Thread t = new Thread(si);
t.start();
//主线程休眠2秒,从而确保刚才启动的线程有机会执行一段时间
try {
Thread.sleep(2000);
}catch(InterruptedException e){
e.printStackTrace();
}
System.out.println("in main() - interrupting other thread");
//中断线程t
t.interrupt();
System.out.println("in main() - leaving");
}
}
public class PendingInterrupt extends Object {
public static void main(String[] args){
//如果输入了参数,则在mian线程中中断当前线程(亦即main线程)
if( args.length > 0 ){
Thread.currentThread().interrupt();
}
//获取当前时间
long startTime = System.currentTimeMillis();
try{
Thread.sleep(2000);
System.out.println("was NOT interrupted");
}catch(InterruptedException x){
System.out.println("was interrupted");
}
//计算中间代码执行的时间
System.out.println("elapsedTime=" + ( System.currentTimeMillis() - startTime));
}
}
public class InterruptCheck extends Object{
public static void main(String[] args){
Thread t = Thread.currentThread();
System.out.println("Point A: t.isInterrupted()=" + t.isInterrupted());
//待决中断,中断自身
t.interrupt();
System.out.println("Point B: t.isInterrupted()=" + t.isInterrupted());
System.out.println("Point C: t.isInterrupted()=" + t.isInterrupted());
try{
Thread.sleep(2000);
System.out.println("was NOT interrupted");
}catch( InterruptedException x){
System.out.println("was interrupted");
}
//抛出异常后,会清除中断标志,这里会返回false
System.out.println("Point D: t.isInterrupted()=" + t.isInterrupted());
}
}
public class InterruptReset extends Object {
public static void main(String[] args) {
System.out.println(
"Point X: Thread.interrupted()=" + Thread.interrupted());
Thread.currentThread().interrupt();
System.out.println(
"Point Y: Thread.interrupted()=" + Thread.interrupted());
System.out.println(
"Point Z: Thread.interrupted()=" + Thread.interrupted());
}
}
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有