建立线程的方法: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