簡體   English   中英

關於java中的Runnable接口的問題?

[英]Question about Runnable Interface in java?

實現線程的一種方法是這樣的:

  Runnable r1 = new Runnable() { 
    public void run() {
          // my code here
    }
  };  

  Thread thread1 = new Thread(r1);
  thread1.start();

現在,如果我堅持使用這個簡單的方法,那么無論如何都要從該線程外部傳遞一個運行塊內的值。 例如,我在運行中的代碼包含一個邏輯,該邏輯需要來自將在調用時使用的進程的輸出流。

如何將此流程流對象傳遞給此運行塊。

我知道還有其他方法,比如實現runnable或extenting thread,但是你能告訴我如何使用上面的方法完成這個。

您可以使用本地final變量:

final OutputStream stream = /* code that creates/obtains an OutputStream */

Runnable r1 = new Runnable() { 
  public void run() {
      // code that uses stream here
  }
};  

Thread thread1 = new Thread(r1);
thread1.start();

final變量對匿名內部類是可見的,比如上面的Runnable

如果您的Runnable變得足夠復雜,那么您應該考慮將其變為命名類。 此時,構造函數參數通常是傳遞參數的最佳機制。

這個答案假設您在啟動線程時沒有使用OutputStream ,但稍后會獲得它。 如果您已經有流對象引用,則應該使用Laurence的示例。


您可以使用一些包裝類,如下所示:

// This is a very simplified example; use getters and setters instead.
class OutputStreamWrapper {
    public OutputStream outputStream;
}

然后你可以這樣做:

final OutputStreamWrapper wrapper = new OutputStreamWrapper();

Runnable r1 = new Runnable() { 
  public void run() {
    // use wrapper.outputStream in here when appropriate
  }
};  

Thread thread1 = new Thread(r1);
thread1.start();

然后,您可以將wrapper變量引用的對象傳遞給其他方法或類,而這些方法或類又將outputStream屬性設置為將流傳遞給線程代碼。

請注意,這是一種黑客攻擊; 在另一個類上實現Runnable並給它這樣一個字段會更好。

對的,這是可能的。 run方法內部,您可以訪問封閉方法中具有final限定符的所有變量。

public void demo() {
  final int accessible = 123;
  int notAccessible = 456;
  new Thread(new Runnable() {
    public void run() {
      System.out.println(accessible);
    }
  }.start());
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM