Runnable接口

来源:互联网 发布:简述网络安全技术 编辑:程序博客网 时间:2024/06/16 04:03

public interface Runnable

The Runnable 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 run.
Runnable接口应该被一个要通过线程执行其实例的类所实现。这个类必须定义一个无参的run方法。
This interface is designed to provide a common protocol for objects that wish to execute code while they are active. For example, Runnable is implemented by class Thread. Being active simply means that a thread has been started and has not yet been stopped.
Runnable接口为那些希望在活动时执行代码的对象提供了一个公共协议。比如,Runnable实现了Thread类,活动的意思是说一个线程已经开始并且还没结束。
In addition, Runnable provides the means for a class to be active while not subclassing Thread. A class that implements Runnable can run without subclassing Thread by instantiating a Thread instance and passing itself in as the target.
而且,Runnable为那些非Thread子类提供了激活方法。一个非Thread子类并实现了Runnable接口的类可以通过实例化一个Thread实例并把自己作为参数传入所执行。

class Demo implements Runnable{    @Override    public void run() {            //要执行的代码        }    }}Demo d = new Demo();Thread t = new Thread(d);t.start();

In most cases, the Runnable interface should be used if you are only planning to override the run() method and no other Thread methods. This is important because classes should not be subclassed unless the programmer intends on modifying or enhancing the fundamental behavior of the class.
大多数情况下,如果你只是打算覆盖run()方法而没有其他的线程方法,就应该用Runnable接口。这点很重要,因为一个类不该被子类化,除非你打算改变或者增强这个类的基本行为。

这里写图片描述

0 0