Als Teil unserer Kursarbeit an der Universität müssen wir einen Multi-Threading-Download-Server in Java erstellen. Alles läuft reibungslos, bis auf eine Kleinigkeit: Der Server muss die Gesamtzahl der Downloads für jedes Element anzeigen, wenn es heruntergeladen wird. Bis jetzt habe ich es geschafft, dass es funktioniert, wenn nicht beide Clients es gleichzeitig anfordern. Der Code ist unten, wenn jemand irgendwelche Ideen hat, wäre ich sehr dankbar. Auch müssen wir thread.sleep Teil enthalten und müssen den Zähler in dieser verworrenen Weise zu erhöhen.
//Snipper from Protocol.java
if (theInput.equals("1")) {
theOutput = "The program displays a message... Another? Y or N";
DownloadCounter counter = new DownloadCounter();
count = DownloadCounter.getcount();//count is a var in Protocol.java it is static
int tmp = count;
try {
Thread.sleep(5000);
} catch (InterruptedException ex) {
System.out.println("sleep interrupted");
}
count = tmp + 1;
DownloadCounter.setcount(count);
System.out.println("Download Total " + count);
state = ANOTHER;
Der DownloadCounter:
//DownloadCounter.java
public class DownloadCounter {
private static int count;
public static synchronized int getcount(){
return count;
}
public static synchronized void setcount(int num){
DownloadCounter.count = num;
}
}