2012-02-01 7 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キーワードの使用方法を学びたかったと推測しています。 –

+0

..また 'DownloadCounter'メソッドの' incrementAndGet'は静的でなければなりません。 – Qwerky

答えて

1

キーワード​​を使用する必要があります。カウンタへの各アクセスは、同じオブジェクトをロックする​​ブロック内にある必要があります。static synchronizedクラスのメソッドまたは明示的にロックするブロックTheClass.classです。

0

ロック機構を使用するとよいでしょう。これは宿題なので、私は指摘したいと思いますOracle Tutorial

0

揮発性物質の使用は許可されていますか?

いつでも同期を使用して回避することができます。