第7段视频,interrupt中断异常。
老师讲的过程,t1.interrupt(); 主函数执行完后,flag不是改成false了吗,为什么线程还是挂起了?老师说还是true?? 看执行的结果也是先打印的over,后打印的线程执行结果的呀,flag怎么能还是true呢?
还有抛出异常的问题,try和catch是处理wait抛出的异常,API中介绍interrupt也抛出异常啊,抛哪去了?在哪处理的?各种迷糊,看三天没看懂,郁闷。。。
class StopThread implements Runnable
{
private boolean flag =true;
public synchronized void run()
{
while(flag)
{
try{wait();}
catch(InterruptedException e)
{
System.out.println(Thread.currentThread().getName()+"....Exception");
}
System.out.println(Thread.currentThread().getName()+"....run");
}
}
public void changeFlag()
{
flag = false;
}
}
class StopThreadDemo
{
public static void main(String[] args)
{
StopThread st = new StopThread();
Thread t1 = new Thread(st);
Thread t2 = new Thread(st);
t1.start();
t2.start();
int num = 0;
while(true)
{
if(num++ == 60)
{
st.changeFlag();
t1.interrupt();
t2.interrupt();
break;
}
System.out.println(Thread.currentThread().getName()+"......."+num);
}
System.out.println("over");
}
}
|