A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

© heheka123 中级黑马   /  2014-4-23 11:48  /  869 人查看  /  1 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

先看代码!
  1. class Demo implements Runnable
  2. {
  3.     public synchronized void run()
  4.     {
  5.         try
  6.         {
  7.                 wait();
  8.         }
  9.         catch (InterruptedException e)
  10.         {
  11.         }
  12.         for (int x = 0;x<100 ;x++ )
  13.         {
  14.             System.out.println(Thread.currentThread().getName()+"..."+x);
  15.         }
  16.     }
  17. }

  18. class  Demo4
  19. {
  20.     public static void main(String[] args) throws Exception
  21.     {
  22.         Demo d = new Demo();
  23.         Thread t1 = new Thread(d);
  24.         t1.join();
  25.         t1.start();
  26.         for (int x = 0;x<100;x++ )
  27.         {
  28.             System.out.println("main..."+x);
  29.         }
  30.         System.out.println("Over!");
  31.     }
  32. }
复制代码


在看老师视频时候,老师说join方法是用再start()前面,该线程执行完才执行其他线程,可是我让t1线程进去后wait那了, 为什么还能执行main呢

评分

参与人数 1技术分 +1 收起 理由
ily521125 + 1

查看全部评分

1 个回复

倒序浏览
  1. class Demo implements Runnable
  2. {
  3.     public synchronized void run()
  4.     {
  5.         try
  6.         {
  7.                Thread.sleep(5000);

  8.                        
  9.         }
  10.         catch (InterruptedException e)
  11.         {
  12.         }
  13.                 for (int x = 0;x<100 ;x++ )
  14.                 {
  15.                         System.out.println(Thread.currentThread().getName()+"..."+x);
  16.                 }
  17.     }
  18. }

  19. class  Demo4
  20. {
  21.     public static void main(String[] args) throws Exception
  22.     {
  23.         Demo d = new Demo();
  24.         Thread t1 = new Thread(d);
  25.         t1.start();
  26.                 t1.join();
  27.         
  28.         for (int x = 0;x<100;x++ )
  29.         {
  30.             System.out.println("main..."+x);
  31.         }
  32.         System.out.println("Over!");
  33.     }
  34. }
复制代码

我试了一下,把t1.join()放到t1.start后面,就产生阻塞效果了。
查了一下API,对于join方法的描述是这样的:
join
public final void join()
                throws InterruptedException等待该线程终止。

抛出:
InterruptedException - 如果任何线程中断了当前线程。当抛出该异常时,当前线程的中断状态 被清除。
那么既然是等待该线程中止,应该是线程启动之后再执行这个动作吧?在线程启动之前就等待过了该线程中止,那么线程启动以后不就是不等待了么?我的理解是这样,不知道对不对。

评分

参与人数 1技术分 +1 收起 理由
ily521125 + 1

查看全部评分

回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马