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
接口。這點很重要,因爲一個類不該被子類化,除非你打算改變或者增強這個類的基本行爲。