2011-02-12 28 views
3
public static void main(String args[]) throws Exception { 
    int maxScore = 0; 

Thread student = new Thread(client,????); 
student.start(); 
} 

我想讓學生線程更改maxScore的值,如何在Java中執行此操作? (就像在C中我們可以通過maxScore的地址)通過運行線程更改主方法中變量x的值

回答

4

你不能。您無法從另一個線程更改局部變量的值。

但是,您可以使用具有int字段的可變類型,並將其傳遞給新線程。例如:

public class MutableInt { 
    private int value; 
    public void setValue(..) {..} 
    public int getValue() {..}; 
} 

(Apache的公地郎提供MutableInt類可以重用)

更新:對於一個全局變量,你可以簡單的使用public static領域。請注意,如果您不僅希望在其中存儲某些值,而且還要根據這些值來讀取它們,則需要使用​​塊或AtomicInteger,具體取決於使用情況。

+0

其實我是想,所有的線程可以訪問讀取值,改變值的全局變量。有什麼辦法嗎? – John 2011-02-12 23:11:45

7

如果要修改單獨線程中的值,則需要一個類對象。例如:

public class Main { 

    private static class Score { 
     public int maxScore; 
    } 

    public static void main(String args[]) throws Exception { 
     final Score score = new Score(); 
     score.maxScore = 1; 

     System.out.println("Initial maxScore: " + score.maxScore); 

     Thread student = new Thread() { 

      @Override 
      public void run() { 
       score.maxScore++; 
      } 
     }; 

     student.start(); 
     student.join(); // waiting for thread to finish 

     System.out.println("Result maxScore: " + score.maxScore); 
    } 
} 
0

將同步到方法對我來說是一個解決方案,謝謝

相關問題