建立線程的方法:java
首先咱們查看Runnable接口的定義:bash
package java.lang; @FunctionalInterface public interface Runnable { public abstract void run(); }
單純經過代碼,咱們能夠獲得的信息有:less
關於Runnable接口更多詳細的說明,我想沒有什麼是比官方文檔更精確的了:ide
/** * The <code>Runnable</code> interface should be implemented by any * class whose instances are intended to be executed by a thread. The * class must define a method of no arguments called <code>run</code>. * <p> * This interface is designed to provide a common protocol for objects that * wish to execute code while they are active. For example, * <code>Runnable</code> is implemented by class <code>Thread</code>. * Being active simply means that a thread has been started and has not * yet been stopped. * <p> * In addition, <code>Runnable</code> provides the means for a class to be * active while not subclassing <code>Thread</code>. A class that implements * <code>Runnable</code> can run without subclassing <code>Thread</code> * by instantiating a <code>Thread</code> instance and passing itself in * as the target. In most cases, the <code>Runnable</code> interface should * be used if you are only planning to override the <code>run()</code> * method and no other <code>Thread</code> methods. * This is important because classes should not be subclassed * unless the programmer intends on modifying or enhancing the fundamental * behavior of the class. * * @author Arthur van Hoff * @see java.lang.Thread * @see java.util.concurrent.Callable * @since JDK1.0 */
翻譯下:函數
關於run方法的註釋:線程
/** * When an object implementing interface <code>Runnable</code> is used * to create a thread, starting the thread causes the object's * <code>run</code> method to be called in that separately executing * thread. * <p> * The general contract of the method <code>run</code> is that it may * take any action whatsoever. * * @see java.lang.Thread#run() */
翻譯下:
當一個實現了Runnable接口的類被用來建立一個線程時,開始這個線程會在這個單獨的線程裏執行run方法裏的代碼。run方法設計的理念就是它能夠用來幹任何事。翻譯
看到這裏應該說Runnable接口的設計理念和用途已經很是清晰了,簡單來講,它就是定義了一個規範,規定任何須要建立線程執行的代碼都應該實現runnable接口,並把代碼放入到run方法中。當線程啓動時,就會在這個線程中執行run方法中的代碼。設計
下面寫一個簡單的示例來演示Runnable接口的使用:code
package org.xtf2009.concurrent.runnable; public class RunnableDemo implements Runnable { @Override public void run() { System.out.println("I am running in Thread:" + Thread.currentThread().getName()); } public static void main(String[] args) { System.out.println("Start main in Thread:"+ Thread.currentThread().getName()); Thread t = new Thread(new RunnableDemo());//建立一個Thread類,傳入RunnableDemo的實例 t.start();//線程啓動後,就會執行run方法中的代碼 System.out.println("End main in Thread:"+ Thread.currentThread().getName()); } }
看下輸出結果:對象
Start main in Thread:main End main in Thread:main I am running in Thread:Thread-0