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

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© kane 中级黑马   /  2014-12-5 11:21  /  1107 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

当启动线程1和线程2的时候,这时通过join()把主线程交给线程1来运行,之后线程1进入无限等待,这个时候线程2还在执行,就可以通过线程2来使用interrupt()方法唤醒主函数,从而线程2和主函数交替执行,这样就可以完成执行所有语句。如果线程1和线程2执行同一个方法,就要在进入无限等待前使用interrupt()方法唤醒主函数。
这就是我最近问题的总结,附件中有两组代码,希望对大家有帮助。



  1. class Dem implements Runnable
  2. {
  3.         private Thread main;
  4.         public Dem(Thread main)
  5.         {
  6.              this.main = main; //获取主线程

  7.         }



  8.         public synchronized  void run()//t1线程执行的方法
  9.         {        
  10.                         try
  11.                         {
  12.                                 main.interrupt();//唤醒主线程
  13.                                                 wait();                                
  14.                                                 
  15.                         }
  16.                         catch(InterruptedException e)
  17.                         {
  18.                                 System.out.println(Thread.currentThread().getName()+"---t1--Exception---");


  19.                         }

  20.                         System.out.println(Thread.currentThread().getName()+"---t1---RUN----");
  21.         }
  22. }



  23. class InterruptDemo
  24. {
  25.         public static void main(String[] args) throws Exception
  26.         {

  27.                 Thread main = Thread.currentThread();//获得主线程的引用。
  28.   

  29.                 Dem d=new Dem(main);
  30.                
  31.                 Thread t1=new Thread(d);
  32.                 Thread t2=new Thread(d);


  33.                 t1.start();
  34.                 t2.start();
  35.                   try
  36.                  {
  37.                                         t1.join();
  38.                  }
  39.                  catch (InterruptedException e)
  40.                  {
  41.                                          System.out.println(Thread.currentThread().getName()+"---main--Exception---");
  42.                  }
  43.                 for(int x=0;x<40;x++)
  44.                 {

  45.                         System.out.println(Thread.currentThread().getName()+"---main-----"+x);        

  46.                 }

  47.                 System.out.println("over");
  48.                                 t1.interrupt();
  49.                                 t2.interrupt();
  50.         }
  51. }
复制代码



关于join()和interrupt()方法.rar

1.53 KB, 下载次数: 17

评分

参与人数 1技术分 +1 收起 理由
船长 + 1 赞一个!

查看全部评分

0 个回复

您需要登录后才可以回帖 登录 | 加入黑马