2011-11-28 24 views
0

我試圖創建我的第一個服務器,一個簡單的聊天服務器。試圖弄清楚如何使用Runnable線程類將參數傳遞給線程

我有一個Runnable類叫做cCleanThread創建使用休眠調用 çGlobals.mUserList.Clean();每10秒一個線程。

我想擁有它,因此cCleanThread的每個實例都會有自己的mUserList對象。我找不出一個簡單的方法來做到這一點。

我想我會somw當我創建我的cCleanThread對象時,如何通過mUserList的參數?

代碼

public class cCleanThread implements Runnable { 

Thread runner; 
public cCleanThread() { 
} 

public cCleanThread(String threadName) { 
    runner = new Thread(this, threadName); // (1) Create a new thread. 
    System.out.println(runner.getName()); 
    runner.start(); // (2) Start the thread. 
} 

public void run() { 
    //Display info about this particular thread 
    System.out.println(Thread.currentThread()); 
    while(true) 
    { 

     try { 
      Thread.sleep(20*1000); 
     } catch (InterruptedException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
     cGlobals.mUserList.Clean(); 
    } 
} 
} 
+0

可能重複[我如何將一個變量傳遞給一個新的Runnable聲明?](http://stackoverflow.com/questions/4297261/how-can-i-pass-a-variable-into-a-new-runnable-declaration) – Ralph

回答

1

傳遞mUserList給線程構造函數:

public class cCleanThread implements Runnable { 

    private final UserList localUserList; 

    public cCleanThread(String threadName, UserList mUserList) { 
     this.localUserList = mUserList; 
     //... 
    } 

    public void run() { 
     //... 
     localUserList.Clean(); 
    } 
} 

的只是創建線程使用不同的參數:

Thread first = new cCleanThread("Thread-Foo", fooUsers); 
Thread second = new cCleanThread("Thread-Bar", barUsers); 
+0

嗨,謝謝,我正在學習這個項目,我正在學習java。 –

1

添加mUserList爲實例變量cCleanThread類,並在構造函數初始化。由於每個線程都對應於cCleanThread實例的實例,因此每個線程只會有一個mUserList。這個mUserList實例可以通過run()方法訪問,因爲它們都在同一個類中。

2

這不是一個答案。這更像是一種改進。

如果你想每10秒運行一次,你可以使用Timer類。這是example。該線程會自動爲您完成。

+0

計時器處於Swing包中。你確定它的依賴嗎? –

+0

對不起,我已將鏈接更改爲java.util.Timer。 – gigadot