[英]understanding java code for thread
我剛剛查看了一些java代碼,我遇到了以下程序
public class LengthOfString extends Thread {
static String s;
public void run(){
System.out.println("You Have Enter String: " + s +" Length Of It is :" + s.length());
}
public static void main(String[] args) throws InterruptedException {
s = "This IS String";
LengthOfString h = new LengthOfString(); //creating the object of class
Thread t = new Thread(h); //why we have passed this object here???
t.start();
}
}
我知道它用於打印字符串長度,但我在理解注釋行時遇到問題。 請幫助我理解為什么使用這個實現。
實際上在java中,有兩種方法可以創建一個Thread 。
提供Runnable對象。 Runnable接口定義了一個run方法,用於包含線程中執行的代碼。 Runnable對象被傳遞給Thread構造函數。
子類線程。 Thread類本身實現了Runnable,盡管它的run方法什么都不做。 應用程序可以子類化Thread,提供自己的run實現。
你選擇了第二個,你可以簡單地寫
new LengthOfString().start();
代替
LengthOfString h=new LengthOfString(); //creating the object of class
Thread t=new Thread(h); //why we have passed this object here???
t.start();
編輯:
Thread類有一個構造函數public Thread(Runnable target)
,它將Runnable
類型作為參數,當你將它傳遞給線程類時,它會在你啟動該線程時調用run()
方法的實現。
在這種情況下,您不需要Thread t = new Thread(h)行,因為LengthOfString擴展了Thread。 但很多時候,您實現了Runnable接口。 在這種情況下,您需要在構造函數中創建一個帶有Runnable參數的Thread對象,因為Runnable Objects沒有啟動方法
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.