java线程理解

本文详细解析了Java中线程的启动机制,包括通过继承Thread类和实现Runnable接口两种方式创建线程的具体过程及区别。重点阐述了start方法如何触发线程的run方法执行,并解释了为何不能重复启动同一个线程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

// 线程的理解,传统上有两种方式,一种是直接new Thread 大家可以想象,为什么掉start方法就
//  可以运行run方法呢?大家可以看Thread的源代码
     /**
      * Causes this thread to begin execution; the Java Virtual Machine
      * calls the <code>run</code> method of this thread.
      * <p>
      * The result is that two threads are running concurrently: the
      * current thread (which returns from the call to the
      * <code>start</code> method) and the other thread (which executes its
      * <code>run</code> method).
      * <p>
      * It is never legal to start a thread more than once.
      * In particular, a thread may not be restarted once it has completed
      * execution.
      *
      * @exception  IllegalThreadStateException  if the thread was already
      *               started.
      * @see        #run()
      * @see        #stop()
      */
     public synchronized void start() {
         /**
   * This method is not invoked for the main method thread or "system"
   * group threads created/set up by the VM. Any new functionality added
   * to this method in the future may have to also be added to the VM.
   *
   * A zero status value corresponds to state "NEW".
          */
         if (threadStatus != 0)
             throw new IllegalThreadStateException();
         group.add(this);
         start0();
         if (stopBeforeStart) {
      stop0(throwableFromStop);
  }
     }
方法说的很明白,Java 虚拟机调用该线程的 run 方法。
结果是两个线程并发地运行;当前线程(从调用返回给 start 方法)和另一个线程(执行其 run 方法)。
多次启动一个线程是非法的。特别是当线程已经结束执行后,不能再重新启动。 
eg:
//  Thread thread = new Thread(){
//   @Override
//   public void run() {
//    while(true){
//     try {
//      Thread.sleep(500);
//     } catch (InterruptedException e) {
//      e.printStackTrace();
//     }
//    }
//   }
//  };
//  thread.start();
// 

//  这是第二种方式,可以看Thread.java的第二种构造方式
 /**
  * If this thread was constructed using a separate
  * <code>Runnable</code> run object, then that
  * <code>Runnable</code> object's <code>run</code> method is called;
  * otherwise, this method does nothing and returns.
  * <p>
  * Subclasses of <code>Thread</code> should override this method.
  *
  * @see     #start()
  * @see     #stop()
  * @see     #Thread(ThreadGroup, Runnable, String)
  */
 public void run() {
 if (target != null) {
     target.run();
 }
 }
可以看出当targer不等于null的时候,我们执行target的run方法。这个target是构造时候传入
进来的runnable对象。可以,下面是线程的第二种方式
//  Thread thread2 = new Thread(new Runnable(){
//   @Override
//   public void run() {
//    while(true){
//     try {
//      Thread.sleep(500);
//     } catch (InterruptedException e) {
//      e.printStackTrace();
//     }
//    }    
//    
//   }
//  });
//  thread2.start();
  
思考下面的代码,是打印出什么呢?是runnable还是thread?答案是肯定的,答应thread。
因为此时new thread()代表是thread的子类,而且我们覆盖了父类的run方法,所以,当执行
start方法的时候,我们去子类寻找,如果找到了run,就不去父类找了。当子类不存在的时候,
然后去父类里面判断target是否为空,即runnable的run方法、

说道这里,大家思考下,为什么我们写代码基本都是用的第二种线程的书写方式呢?他有什么好处?
其实,好处谈不上,只是说,第二种线程的方法,更加能体现java的面向对象的思想。构造方法里面
传入的参数也是对象,彼此的结构封装的很好。
  new Thread(
    new Runnable(){
     public void run() {
      while(true){
       try {
        Thread.sleep(500);
       } catch (InterruptedException e) {
        e.printStackTrace();
       }
       System.out.println("runnable");

      }       
     }
    }
  ){
   public void run() {
    while(true){
     try {
      Thread.sleep(500);
     } catch (InterruptedException e) {
      e.printStackTrace();
     }
     System.out.println("thread ");

    } 
   }
  }.start();
  
  
 }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值