2017-02-27 70 views
0
public static int do_dispatch(){ 

     { 
      int prior = this.getPriority(); 
      ThreadCB threadToDispatch=null; 
      ThreadCB runningThread=null; 
      TaskCB runningTask=null; 
      try { 
       runningTask = MMU.getPTBR().getTask(); 
       runningThread = runningTask.getCurrentThread(); 
      } catch(NullPointerException e) {} 

      // If necessary, remove current thread from processor and reschedule it. 
      if(runningThread != null) 
      { 
       // Check if quantum is exceeded 
       if (HTimer.get() < 1) 
       { 
        //Increment the priority to lower priority value 
        prior++; 
        this.setPriority(prior); 
       } 


       //Append to expired 
       expired[prior].append(this); 

       runningTask.setCurrentThread(null); 
       MMU.setPTBR(null); 
       runningThread.setStatus(ThreadReady); 
       readyQueue.append(runningThread); 

又如:什麼是靜態方法來實現「這個」關鍵字的正確途徑

class Sub { 
    static int y; 
    public static void foo() { 
     this.y = 10; 
    } 
} 

我試圖編譯我的計劃,但我繼續使用得到的錯誤在這種情況下這個關鍵字。我明白'this'代表調用該方法的對象,並且靜態方法不會綁定到任何對象。

實施'this'的正確方法是什麼?

+2

你不能「執行」這個''。 [在語言規範中定義](https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.8.3),這是編譯時錯誤在靜態方法中使用它。 –

+2

'this'指向類的當前實例,並且在靜態上下文中不存在實例 - 所有方法和屬性都處於類級別(又名 - 它們在類的所有實例之間共享)。爲了處理你在代碼中顯示的方法的靜態屬性,你可以用類名前綴它,比如'Sub.y = 10'。請注意,您不需要在此處執行此操作,因爲您沒有隱藏任何現有屬性。即:'y = 10'應該足夠了。 –

+1

**請勿自行放置自己的帖子。**您的編輯使您的問題難以理解。 – EJP

回答

0

執行「this」的正確方法是什麼?

你根本無法實現。在靜態方法中沒有this的概念。

我試圖編譯我的計劃,但我仍然得到錯誤與 使用this關鍵字在這種情況下

你如何解決這個問題?

您可以:

  • 傳遞任何對象的引用您的靜態方法和使用。

  • 讓你的屬性和方法的實例fields/methods
0

您不能「執行」thisIt's a keyword defined in the language spec,並且在靜態方法中使用它是一個編譯時錯誤。

如果你想指的是含有類的實例,你總是可以在一個實例作爲參數傳遞:

public static int do_dispatch(YourClass that){ 
    int prior = that.getPriority(); 
    // ... 

但要注意:1)不能調用變量this; 2)這基本上只是一個實例方法,那麼爲什麼使它成爲static(即,你可以使它成爲一個非靜態方法,你調用的就像that.do_dispatch(),而不是do_dispatch(that))?

0

你不行。在靜態方法中沒有this的概念。您必須執行以下操作之一:

  • 使該方法不是靜態的。
  • 僅引用靜態成員(請注意,靜態成員變量在所有靜態方法的調用和其他地方共享)。如果你的代碼實際上不需要任何類定義的特定實例do_dispatch,這將是最合適的選擇。
  • 將任何對象的實例傳遞給靜態方法,然後對其進行操作。

查看the official tutorial瞭解一下。如果以上選項都不能用於爲程序提供正確的行爲,那麼您必須根據您在此處瞭解的有關靜態類的內容重新思考您的基本設計。

0

你不能,你不需要。只要刪除this.y在上下文中是明確的。

+0

什麼是'y'?我在OP的代碼中看不到它。 –

+0

@AndyTurner'this.y = 10;'中的''是給他編譯器錯誤,他正試圖修復。 – EJP

+0

還有'this.setPriority'。 –

相關問題