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
接口。这点很重要,因为一个类不该被子类化,除非你打算改变或者增强这个类的基本行为。