我設計了一個服務器 - 客戶端應用程序使用Java,我已經連接到服務器的一個以上的用戶。 服務器提供了一些功能,如:如何實現同步多線程中的Java應用程序
- 下載文件
- 創建文件
- 書面方式/附加文件等
我發現需要同步的一些問題當兩個或更多的用戶發送相同的請求時。
例如:當用戶想下載同一個文件的同時,如何同步使用synchronized塊或任何其他方法這個動作?
//main (connecting 2 users in the server)
ServerSocket server= new ServerSocket(8080, 50);
MyThread client1=new MyThread(server);
MyThread client2=new MyThread(server);
client1.start();
client2.start();
這裏是我想同步方法:
//outstream = new BufferedWriter(new OutputStreamWriter(sock.getOutputStream()));//output to client
//instream = new BufferedReader(new InputStreamReader(sock.getInputStream()));//input from client
public void downloadFile(File file,String name) throws FileNotFoundException, IOException {
synchronized(this)
{
if (file.exists()) {
BufferedReader readfile = new BufferedReader(new FileReader(name + ".txt"));
String newpath = "../Socket/" + name + ".txt";
BufferedWriter socketfile = new BufferedWriter(new FileWriter(newpath));
String line;
while ((line = readfile.readLine()) != null) {
outstream.write(line + "\n");
outstream.flush();
socketfile.write(line);
}
outstream.write("EOF\n");
outstream.flush();
socketfile.close();
outstream.write("Downloaded\n");
outstream.flush();
} else {
outstream.write("FAIL\n");
}
outstream.flush();
}
}
注意:此方法是在擴展Thread,當我想正在使用的一類到「下載」文件中的覆蓋方法run()的
請問這個例子向我保證,當用戶想下載同一個文件其中一人將不得不等待?另一個會得到它嗎?謝謝你的時間!
也許你會在這裏找到答案:[什麼'同步'是什麼意思?](http://stackoverflow.com/questions/1085709/what-does-synchronized-mean) – Sergey
我閱讀它,我理解它,但我不知道如何在我的例子中 – Phill