【发布时间】:2014-02-14 20:11:20
【问题描述】:
我知道有很多关于线程同步的问题,但没有人给我解释如何在我的实现中使用它。所以我有一个等待客户端连接的服务器,因为在连接时为每个连接的客户端创建一个线程,从每个客户端发送的每条消息都将显示在服务器中,并带有 clientIP>>,然后每个客户端将从服务器检索此消息,以便每个客户端都有相同的消息。类似于 mIRC 可能会添加..
好吧,问题解决了:
我在链表中保存每个连接的客户端的会话实例。
我的会话类很简单:
public class Session extends Thread{
private Socket soc;
public BufferedReader in;
public PrintWriter out;
public Session(Socket in_client){
//soc = new Socket();
soc = in_client;
this.start();
}
@Override
public void run() {
try{
in = new BufferedReader(new InputStreamReader(soc.getInputStream()));
out = new PrintWriter(soc.getOutputStream(), true);
String inputLine;
while(true){
if((inputLine = in.readLine()) != null){
textArea.append("Client IP["+soc.getInetAddress()+"]: " + inputLine+"\n");
for(Session s:dstruct)
s.out.println(s.soc.getInetAddress()+">"+inputLine);
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}catch(IOException e ){
try {
in.close();
out.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}}
}
}
在服务器线程运行方法中,我创建会话并通过以下方式将它们推送到数据结构链表:
while(true){
if((clientSocket = serverSocket.accept())!=null){
dstruct.push(new Session(clientSocket));
}
现在我将如何使这些线程同步?我已经阅读了许多不同的建议,例如 调用 synchronized(...) 或在方法声明中进行了同步,还阅读了通知,但在通知线程时无法理解这会完成什么, 在这种情况下我会把它放在哪里? 我有一个服务器线程检查客户端将它们连接到由 Thread 扩展的会话。主线程应该同步子线程还是应该有一些同步方法来同步它们?
【问题讨论】:
-
您显示了将会话添加到列表的位置,但是您从哪里开始线程?
-
你一定是指main方法中启动的主线程,
-
Server类有一个main方法启动线程然后跳转到run方法希望澄清一下,子线程是在session的构造函数中启动的。
-
请正确格式化您的帖子(看看代码是如何格式化的),这将使您有更好的机会获得有意义的答案
标签: java multithreading sockets client-server