什么時候讓線程實現(xiàn)Runnable接口,什么時候讓線程繼承Thread類?
JDK幫助文檔中的原話:Runnable 接口應(yīng)該由那些打算通過某一線程執(zhí)行其實例的類來實現(xiàn)
(不明白是啥意思)
孫鑫老師的原話:當不需要改變一個線程中除了run()方法以外的其他方法時,讓線程實現(xiàn)Runnable接口。
(明白是什么意思,但不知道有什么用 汗!!!)
如果讓一個線程實現(xiàn)Runnable接口,那么當調(diào)用這個線程的對象開辟多個線程時,可以讓這些線程調(diào)用同一個變量;若這個線程是由繼承Thread類而來,則要通過內(nèi)部類來實現(xiàn)上述功能,利用的就是內(nèi)部類可任意訪問外部變量這一特性。
例子程序:
public class ThreadTest
{
public static void main(String[] args)
{
MyThread mt=new MyThread();
new Thread(mt).start(); //通過實現(xiàn)Runnable的類的對象來開辟第一個線程
new Thread(mt).start(); //通過實現(xiàn)Runnable的類的對象來開辟第二個線程
new Thread(mt).start(); //通過實現(xiàn)Runnable的類的對象來開辟第三個線程
//由于這三個線程是通過同一個對象mt開辟的,所以run()里方法訪問的是同一個index
}
}
class MyThread implements Runnable //實現(xiàn)Runnable接口
{
int index=0;
public void run()
{
for(;index<=200;)
System.out.println(Thread.currentThread().getName()+":"+index++);
}
}
------------------------------------------------------------------------------------------------------------------------------------
public class ThreadTest
{
public static void main(String[] args)
{
MyThread mt=new MyThread();
mt.getThread().start(); //通過返回內(nèi)部類的對象來開辟第一個線程
mt.getThread().start(); //通過返回內(nèi)部類的對象來開辟第二個線程
mt.getThread().start(); //通過返回內(nèi)部類的對象來開辟第三個線程
//由于這三個線程是通過同一個匿名對象來開辟的,所以run()里方法訪問的是同一個index
}
}