黑马程序员技术交流社区

标题: 问个线程的问题! [打印本页]

作者: heheka123    时间: 2014-4-23 11:48
标题: 问个线程的问题!
先看代码!
  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呢
作者: kuroro自走核炮    时间: 2014-4-23 12:15
  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 - 如果任何线程中断了当前线程。当抛出该异常时,当前线程的中断状态 被清除。
那么既然是等待该线程中止,应该是线程启动之后再执行这个动作吧?在线程启动之前就等待过了该线程中止,那么线程启动以后不就是不等待了么?我的理解是这样,不知道对不对。





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