黑马程序员技术交流社区
标题:
关于多线程的程序运行问题问题
[打印本页]
作者:
陆堂杰
时间:
2013-7-28 22:31
标题:
关于多线程的程序运行问题问题
本帖最后由 杨兴庭 于 2013-7-30 22:38 编辑
class MyThread implements Runnable{
public void run(){
System.out.println("1、进入run()方法") ;
try{
Thread.sleep(5000) ; // 线程休眠5秒
System.out.println("2、已经完成了休眠") ;
}catch(InterruptedException e){
System.out.println("3、休眠被终止") ;
return ; // 返回调用处
}
System.out.println("4、run()方法正常结束") ;
}
};
public class ThreadInterruptDemo{
public static void main(String args[]){
MyThread mt = new MyThread() ;
Thread t = new Thread(mt,"线程");
t.start() ; // 启动线程
try{
Thread.sleep(2000) ; // 线程休眠2秒
}catch(InterruptedException e){
System.out.println("3、休眠被终止") ;
}
t.interrupt() ; // 中断线程执行,
}
};
上面代码中t.start()运行是一个线程,它运行MyThread中的run()方法,需要休眠5秒。而try{}catch{}代码也是一个线程,它休眠2秒。为什么它休眠2秒后运行t.interrup()方法可以终止run()方法中的5秒休眠,使run()方法只休眠2秒就继续运行了?
作者:
dicegame
时间:
2013-7-28 23:57
为了更好的理解程序是怎么走的
我修改了一下代码
package qbb;
class MyThread implements Runnable{
public void run(){
System.out.println("1、进入run()方法") ;
try{
Thread.sleep(5000) ; // 线程休眠5秒
System.out.println("2、已经完成了休眠") ;
}catch(InterruptedException e){
System.out.println("3、休眠被终止run") ;
return ; // 返回调用处
}
System.out.println("4、run()方法正常结束") ;
}
};
public class ThreadInterruptDemo{
public static void main(String args[]){
MyThread mt = new MyThread() ;
Thread t = new Thread(mt,"线程");
t.start() ; // 启动线程
try{
Thread.sleep(2000) ; // 线程休眠2秒
}catch(InterruptedException e){
System.out.println("3、休眠被终止main") ;
}
t.interrupt() ; // 中断线程执行,
}
};
复制代码
运行结果是:
1、进入run()方法
3、休眠被终止run
分析
t.start()会启动线程t,这时有两个线程t和主线程,它们都有可能抢到CPU的执行权
下面分类讨论
情况一:
假如t先执行,则输出”1、进入run()方法“后,t转入冻结状态(5秒),放弃执行资格
这主线程开始执行,主线程一执行也马上进入了冻结状态(2秒)
但2秒后主线程恢复运行状态,t则继续冻结
然后t.interrupt()让t强制从冻结转入运行(此时主线程结束)
这个异常被catch到,所以输出“3、休眠被终止run”,t结束
情况二:
主线程先执行,并马上转入冻结状态(2秒)
这是t开始运行,输出”1、进入run()方法“后,t也转入冻结(5秒)
但2秒后主线程恢复运行状态,t则继续冻结
然后t.interrupt()让t强制从冻结转入运行(此时主线程结束)
这个异常被catch到,所以输出“3、休眠被终止run”,t结束
这就是线程切换的详细流程
所以无论运行多少遍
运行结果都不会变
作者:
哪颗最亮的星星
时间:
2013-7-29 21:07
这里的interrup方法是中断线程,程序开始从主线程执行起,当执行到interrup时抛出异常,执行catch(InterruptedException e),这时所线程都中断了
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2