月1日,我們應該知道線程(String s)將VS主題(Runnable的R,String s)將不同的目的。
不同的是線程(String s)將我們在支架()發送 「價值」到實現Runnable但線程(Runnable的R,String s)將我們給一個線程名到String構造s到實現Runnable的線程構造函數。
這裏是通過線程實現Runnable的相同代碼(Runnable r,String s)。
public class threadtest implements Runnable{
Thread t;
threadtest th;
public threadtest(){}
public threadtest(String name)
{
System.out.println("satheesh");
Thread t=new Thread(th, name); //satheesh,name of thread, gave to name
t.start(); //2nd thread that will start run() method in void run()
//t=null;
//System.out.println(this+"\n"+t);
}
public void run(){
System.out.println("satheesh");
for(int i=0;i<=10;i++)
{
try{
System.out.println("satheesh");
Thread.sleep(1000);
System.out.print(Thread.currentThread());
}
catch(Exception e) { System.out.println(e); }
}
}
public static void main(String args[]){
//ob is Runnable object that will send his empty value()
threadtest ob = new threadtest(); //to default constructor threadtest() above
//satheesh is name of main thread that we will send to String name in Thread t=new Thread(th, name);
Thread th = new Thread(ob, "satheesh");
th.start(); //1st thread that will instruct to send satheesh
}
}
輸出:
satheesh
satheesh
Thread[satheesh,5,main]satheesh
Thread[satheesh,5,main]satheesh
Thread[satheesh,5,main]satheesh
Thread[satheesh,5,main]satheesh
Thread[satheesh,5,main]satheesh
Thread[satheesh,5,main]satheesh
Thread[satheesh,5,main]satheesh
Thread[satheesh,5,main]satheesh
Thread[satheesh,5,main]satheesh
Thread[satheesh,5,main]satheesh
Thread[satheesh,5,main]satheesh
BUILD SUCCESSFUL (total time: 11 seconds)
你的問題就沒有意義了。 – SLaks 2011-01-26 15:31:09
請澄清,並檢查此線程:http://stackoverflow.com/questions/541487/java-implements-runnable-vs-extends-thread – birryree 2011-01-26 15:31:51
你可能會發現閱讀線程有趣的代碼,特別是run()方法。 – 2011-01-26 15:59:06