java線程理解

來源:互聯網
上載者:User

 

// 線程的理解,傳統上有兩種方式,一種是直接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();
  
  
 }

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.