Runnable接口

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

這裏寫圖片描述

發佈了33 篇原創文章 · 獲贊 23 · 訪問量 7萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章