Runnable其实是java sdk的代码。
1、定义
@FunctionalInterface
public interface Runnable {
/**
* 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();
}
Runnable接口应该被任何希望由线程执行的类实现。该类必须定义一个名为run的无参方法。
这个接口为所有期望在actie时执行代码的对象提供一个共同的协议。例如,Runnable被Thread类实现。”active"表示线程已经启动但尚未停止。
此外,Runnable为一个类提供了一种在不继承Thread的情况下仍然保持活动状态的方式。一个实现Runnable的类可以通过实例化一个Thread对象并将自身作为目标传递来运行,而无需继承Thread类。在大多数情况下,如果只打算覆盖run()方法而不是其他Thread方法,应该使用Runnable接口。
这是因为只有当程序员打算修改或增强类的基本行为时,才应该对类进行子类化。
Runnable 从名字上就可以理解,实现了该接口的类,具备runnable的能力,而所谓的runnable能力,也不过是java约定的,具有run方法。你可以说,拥有fly接口的类,是flyable的,这些都是我们强加上去的概念。
2、使用
使用步骤如下:
(1) 实现Runnable接口
(2) 重写run()方法
(3) 创建runnable实例
(4) 创建执行器实例
(5) 将Runnable实例放入执行器中去执行,例如Thread,ExecutorService等。
(6) 执行器在运行时会调用Runnable接口中的run方法。
Runnable更像是定义了个任务task,执行器是工人,Runnable丢给工人去执行。
一个基本的Runnable实现示例如下:
public class MyRunnable implements Runnable {
@Override
public void run() {
System.out.println("Hello from thread!");
}
}
可以通过以下方式启动一个Runnable任务:
- 将Runnable传递给Thread类的构造函数:
Runnable runnable = new MyRunnable();
Thread thread = new Thread(runnable);
thread.start();
- 使用ExecutorService执行Runnable:
ExecutorService executor = Executors.newSingleThreadExecutor();
executor.execute(new MyRunnable());
executor.shutdown();
- 将Runnable作为Lambda表达式或方法引用传递给ExecutorService:
ExecutorService executor = Executors.newSingleThreadExecutor();
executor.execute(() -> System.out.println("Hello from thread!"));
executor.execute(MyRunnable::run);
executor.shutdown();
我们下一讲将介绍Thread、ExecutorService。