黑马程序员技术交流社区

标题: 对于interrupt与wait的使用 [打印本页]

作者: ysdolls    时间: 2014-8-1 23:27
标题: 对于interrupt与wait的使用
本帖最后由 ysdolls 于 2014-8-3 18:36 编辑

毕老爷12天第9节视频的最后讲的那几句:
如果加入JOIN 主线程等待,而等待的T1线程也挂了,可以用interrupt强制唤醒。
这句没能弄明白,大家谁实现了?
T1 和主线程都挂了 那程序的两个线程不是都结束了 ,那还在哪里调用interrupt呢?
我想试试让T1 wait 结果 杯具如下:

/*
join:
当A线程执行到了B线程的.join()方法时,A就会等待。等B线程都执行完,A才会执行。

join可以用来临时加入线程执行。


*/

class Demo implements Runnable
{
        public void run()
        {
                for(int x=0; x<70; x++)
                {
                        System.out.println(Thread.currentThread().toString()+"....."+x);
//                        Thread.yield();
                        try {
                                wait();
                        } catch (InterruptedException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                        }
                }
        }
}


class  JoinDemo
{
        public static void main(String[] args) throws Exception
        {
                Demo d = new Demo();
                Thread t1 = new Thread(d);
                Thread t2 = new Thread(d);
                t1.start();
               
                //t1.setPriority(Thread.MAX_PRIORITY);
                t1.join();

                t2.start();


                for(int x=0; x<80; x++)
                {
                        System.out.println("main....."+x);
                }
                System.out.println("over");
        }
}

跳出了 一车错误 而程序也运行结束了  求解读
:Q
作者: ysdolls    时间: 2014-8-1 23:29
顺便急求技术分,时间紧迫 谢谢亲们了
作者: fantacyleo    时间: 2014-8-1 23:41
你没有设置同步锁就调用wait,抛IllegalMonitorStateException是必然的。另外,我理解老毕的意思是:t1挂掉之前调用interrupt方法唤醒main
作者: ysdolls    时间: 2014-8-1 23:53
谢谢了,一句话就解决了我的问题。。。。




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2