2012-02-01 19 views
1

我有一個併發服務器,用戶選擇一個顯示選項。每次選擇任何選項時,計數器都會遞增,只顯示所選選項的總數。不同的選項不需要單獨的計數器;只有總數是必需的。併發服務器計數器

引用JAVA API後,最明智的方法似乎是使用原子整數,一切都按預期完美工作。

我公司生產的以下內容:

ServerProtocol.java

public class ServerProtocol { 

private static final int ANOTHER = 2; 
private static final int OPTIONS = 3; 

case OPTIONS: 
    if (theInput.equals("1")) { 
     theOutput = "computer program description here -- Another? Y or N"; 

     DownloadCounter counter = new DownloadCounter(); 
     counter.incrementCount(); 
     System.out.println(counter); 

     TrackDownloads clientDetails = new TrackDownloads(); 
     clientDetails.trackLocalhostAddress(); 
     state = ANOTHER; 
case ANOTHER: 

DownloadCounter.java

import java.util.concurrent.atomic.AtomicInteger; 

public class DownloadCounter { 

    private static AtomicInteger count = new AtomicInteger(0); 

    public void incrementCount() { 
     count.incrementAndGet(); 
    } 

    @Override 
    public String toString() { 
     return "Total Downloads =" + count; 
    } 
} 

的問題是,我的講師已轉頭說我不能使用原子整數!

他們爲我提供了一些我必須包括在我的項目中的代碼。那就是:

int tmp = yourCounter; 
    try { 
     Thread.sleep(5000); 
    } catch (InterruptedException ex) { 
     System.out.println("sleep interrupted"); 
    } 
    yourCounter = tmp + 1; 

問題是我似乎無法同時使用這個計數器。我迄今產生以下:

ServerProtocol.java 

public class ServerProtocol { 

private static final int ANOTHER = 2; 
private static final int OPTIONS = 3; 
private static int yourCounter; 

case OPTIONS: 
    if (theInput.equals("1")) { 
     theOutput = "computer program description here -- Another? Y or N"; 

     int tmp = yourCounter; 
     try { 
      Thread.sleep(5000); 
     } catch (InterruptedException ex) { 
      System.out.println("sleep interrupted"); 
     } 
     yourCounter = tmp + 1; 

     System.out.println("Download Total " + yourCounter); 

     TrackDownloads clientDetails = new TrackDownloads(); 
     clientDetails.trackLocalhostAddress(); 
     state = ANOTHER; 
case ANOTHER:  

採用上述方法,當2或客戶端同時請求選項,yourCounter變量只遞增一次。我期望只有一個客戶端可以同時訪問變量,以確保計數器保持準確。有任何想法嗎?

在此先感謝。

+1

我猜你的講師希望你瞭解同步,或者更準確地說,使用synchronized關鍵字。 – 2012-02-01 15:15:30

+0

..你的'DownloadCounter'方法'incrementAndGet'應該是靜態的。 – Qwerky 2012-02-01 15:18:19

回答

1

您必須使用​​關鍵字。對計數器的每次訪問應位於​​塊中,該塊可鎖定同一對象:該類的static synchronized方法或明確鎖定TheClass.class的同步塊。

0

您是否允許使用揮發性物質?

你總是可以使用一些同步來解決這個問題。