Chinaunix首页 | 论坛 | 博客
  • 博客访问: 202294
  • 博文数量: 66
  • 博客积分: 966
  • 博客等级: 准尉
  • 技术积分: 550
  • 用 户 组: 普通用户
  • 注册时间: 2011-02-11 11:52
文章分类

全部博文(66)

文章存档

2012年(60)

2011年(6)

分类: Java

2012-09-27 15:16:19

创建线程的2中传统方式:
1.在Thread子类覆盖的run方法中编写运行代码;
2.在传递给Thread对象的Runnable对象的run方法中编写代码
3.总结:
       查看Thread类的run()方法的源代码,可以看到其实
这2种方式都是在调用Thread对象的run方法,如果Thread类的run方法没有被覆盖
且为该Thread对象设置了一个Runnable对象,该RUN方法会调用Runnable对象
的Run方法;
4.问题:
       如果在Thread子类覆盖的run方法中编写运行代码,也为thread子类对象
传递了一个Runnable对象,那么,线程运行时的执行代码是子类的run方法的代码?
还是Runnable对象的run方法的代码?
 
源代码如下:TraditionalThread.java  包含上述知识点
         package cn.hinge.yangjun;
public class TraditionalThread  {
    /**
  *
  * @param args
 */
 public static void main(String[] args) {
  
  Thread thread = new Thread(){
  @Override
  public void run() {
   while(true){
                      try {
      Thread.sleep(10000);
     } catch (InterruptedException e) {
      e.printStackTrace();
     }     
                 System.out.println("1:"+Thread.currentThread().getName()); 
                 System.out.println("2:"+this.getName());
    }
     }
     };
  //启动线程,测会调用run方法,但是,此方法没有业务逻辑,如果想用它来做某些事,侧需要子类重写此方法;
  thread.start();
  
  Thread thread2 = new Thread( new Runnable(){
   
   public void run() {
    
    while(true){
                    try {
      Thread.sleep(10000);
     } catch (InterruptedException e) {
      e.printStackTrace();
     }     
                 System.out.println("2:"+Thread.currentThread().getName()); 
    }
    
   }
  });
  
  thread2.start();

  /*
   *  new Thread( new Runnable() ).start() 拆分 成 new Thread( ){ run() }.start 和 new Thred(run()){}  前者是子类重写父类 Thread 类 run方法,后者是通过自己构造方法回调run方法
   *  如下有2个run 方法.一个是子类,一个是父类,子类是重写父类Thread() run 方法,
      而父类是在自己构造函数中通过 new Runable()方法 回写 run()方法
   *  那么在程序运行是会执行那个 run 方法呢?
   *  这个规则是这样的,程序首先执行子类中的run方法,如果子类没有。
      就执行父类中run方法。但是只  执行一个。
   *
   *          
  */
 
  new Thread(new Runnable()//父类
      {
   public void run() {
    while (true) {
     try {
      Thread.sleep(10000);
     } catch (InterruptedException e) {
      e.printStackTrace();
     }
     System.out.println("runnable:"
       + Thread.currentThread().getName());
    }
   }
  }) {
   // thread 子类
   public void run() {
    while (true) {
     try {
      Thread.sleep(10000);
     } catch (InterruptedException e) {
      e.printStackTrace();
     }
     System.out.println("thread:" + Thread.currentThread().getName());
    }
   }
  }.start();
  
  
  
 }
 
}
阅读(1443) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~