2014-04-18 39 views
-1
public void run(){ 
try{for(int i=5;i>0;i--){ 
     System.out.println("My Thread: " +i); 
     t.sleep(2000); 
    }//end of for 
}catch(InterruptedException e){System.out.println("MyThread Interrupted");} 
    System.out.println("MyThread exiting"); } 
}//end of class 

就像我想有兩個線程,唯一的區別是t.sleep(1000)和t1.sleep(2000)。我怎樣才能做到這一點???一個類可以在Java中爲兩個不同的線程使用兩種運行方法嗎?

+2

在如何將參數傳遞給一個線程: http://stackoverflow.com/questions/877096/how-can-i-pass-a-parameter-to-a-java-thread – Egg

+0

FYI ,'sleep'是一個**靜態**方法。當你說't.sleep(2000)'時,什麼't'(甚至可以是'null')都沒有關係。編譯器將它視爲「Thread.sleep(2000)」,這會導致當前線程進入休眠狀態。 – ajb

回答

2

該類應爲sleepTime採取額外的構造函數。

public class MyRunnable implements Runnable() { 
    private final long sleepTime; 

    public MyRunnable(long sleepTime) { 
     this.sleepTime = sleepTime; 
    } 

    @Override public void run() { 
     // ... 
     Thread.sleep(sleepTime); 
    } 
+0

我應該像這樣執行嗎? 'MyRunnable t1 = new MyRunnable(1000); MyRunnable t2 = new MyRunnable(2000); t1.start(); t2.start()' –

相關問題