作爲我們大學課程的一部分,我們必須使用Java構建多線程下載服務器。 除了一點之外,一切都運行平穩:我們必須讓服務器在每次下載時顯示每個項目的總下載次數。到目前爲止,我已經得到它的工作,除非兩個客戶同時要求它。代碼如下,如果任何人有任何ides,我會非常感激。我們還必須包含thread.sleep部分,並且必須以這種複雜的方式增加計數器。Java中的併發下載計數器
//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;
的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;
}
}
+1在生產代碼中,當然我會使用AtomicInteger。另一方面,OP應詢問他們的教授,練習的重點是否準確地在進行簡單解決之前進行同步... – thkala 2012-02-23 18:49:04
@thkala好點,OP應該向他們的教授諮詢瞭解練習的目標(即瞭解同步或原子操作)。 – Kiril 2012-02-23 19:15:26