您的位置:首页 > 其它

Runnable

2018-01-18 20:17 169 查看

Runnable

概述

java version “1.8.0_131”

多线程创建方式之一

public class RunnableTest implements Runnable{

// 实现 run()
public void run() {
System.out.println("thread");
}

public static void main(String[] args) {
RunnableTest test = new RunnableTest();
// 线程启动由Thread负责
Thread thread = new Thread(test);
thread.start();
}
}


Runnable只有一个抽象的run()方法,此方法是在运行时由JVM调用,每一个运行期的Runnable实现类实例(包括Thread的子类,因为Thread亦是实现了Runnable接口)都对应于操作系统中的一个线程,所以说Java中的线程只是操作系统线程的一个映射,Java中线程的运行效率也不可能高于底层语言线程,因为Java中线程的创建和调用需要经过JVM,JVM再向下调用(JNI的方式与特定平台进行通信)

类注释

/**
* 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
*/


Runnable 接口可以被任何想要被一个线程运行的接口继承实现;继承 Runnable 接口的类必须有一个 run() 方法;

Runnable 接口被设计的目的是为那些当其处于活跃期时期望运行代码的对象提供一个公共的协议;处于活跃期简单的说就是一个线程已经启动但还没有结束

继承 Runnable 接口实现线程,不需继承 Thread;而将类本身作为 Thread 中的目标 target

Runnable 接口最好不要继承,除非开发者想要更好的扩展此接口的功能

类注解

@FunctionalInterface
public interface Runnable {
}


@FunctionalInterface
用来标记函数式编程接口

函数式编程接口:指仅仅只包含一个抽象方法的接口

该注解不是必须的,如果一个接口符合”函数式接口”定义,那么加不加该注解都没有影响

加上该注解能够更好地让编译器进行检查。如果编写的不是函数式接口,但是加上了@FunctionInterface,那么编译器会报错

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()
*/
public abstract void run();


当一个对象实现 Runnnable 接口被用来创建一个线程,线程的启动导致该对象的 run 方法被另一个线程调用

参考资料

JDK8新特性:函数式接口@FunctionalInterface的使用说明

Java.lang.Runnable 接口
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Runnable