我試圖存儲任何客戶端從ServerProtocol類請求描述的次數。併發服務器上的共享計數器未按預期遞增
目前,每次新客戶端加入時,計數器將從零開始遞增。有任何想法嗎?
Counter類:
從ServerProtocol類public class Counter {
private int counter;
public synchronized int get() {
return counter;
}
public synchronized void set(int n) {
counter = n;
}
public synchronized void increment() {
set(get() + 1);
}
}
段:
case OPTIONS:
if (theInput.equals("1")) {
theOutput = "computer program description here -- Another? Y or N";
counter.increment();
System.out.println(counter.get());
state = ANOTHER;
println方法上面打印計數器的當前值成在服務器類的終端:
ServerProtocol種類:
public class ServerProtocol {
private static final int TERMS = 0;
private static final int ACCEPTTERMS = 1;
private static final int ANOTHER = 2;
private static final int OPTIONS = 3;
private int state = TERMS;
public String processInput(String theInput) {
String theOutput = null;
Counter counter = new Counter();
switch (state) {
case TERMS:
theOutput = "Terms of reference. Do you accept? Y or N";
state = ACCEPTTERMS;
break;
case ACCEPTTERMS:
if (theInput.equalsIgnoreCase("y")) {
theOutput = "1. computer program 2. picture 3. e-book";
state = OPTIONS;
} else if (theInput.equalsIgnoreCase("n")) {
theOutput = "Bye.";
} else {
theOutput = "Invalid Entry -- Terms of reference. Do you accept? Y or N";
state = ACCEPTTERMS;
}
break;
case ANOTHER:
if (theInput.equalsIgnoreCase("y")) {
theOutput = "1. computer program 2. picture 3. e-book";
state = OPTIONS;
} else if (theInput.equalsIgnoreCase("n")) {
theOutput = "Bye.";
} else {
theOutput = "Invalid Entry -- Another? Y or N";
state = ACCEPTTERMS;
}
break;
case OPTIONS:
if (theInput.equals("1")) {
theOutput = "computer program description here -- Another? Y or N";
counter.increment();
counter.get();
state = ANOTHER;
} else if (theInput.equals("2")) {
theOutput = "picture description here -- Another? Y or N";
state = ANOTHER;
} else if (theInput.equals("3")) {
theOutput = "e-book description here -- Another? Y or N";
state = ANOTHER;
} else {
theOutput = "Invalid Entry -- 1. computer program 2. picture 3. e-book";
state = OPTIONS;
}
break;
default:
System.out.println("Oops");
}
return theOutput;
}
}
您是否每次客戶端加入時都調用processInput?每次調用該方法時,都會創建一個新的計數器。 – Megacan 2011-12-14 19:19:46