这是我的代码。请告诉我第二种方法(ReceiveMSG)为什么不出错?
更清楚的是,在client1连接和client2连接成功之后,
为什么这段代码没有出错?因为实际上这个类有两个threadReceive对象
正在运行,为什么这段代码不是错误?!
P.S。对不起,我的英语很差......这是我的第一篇文章英文文章=口= ||
public class Server{
String msgIN = null, msgOUT = "This is Server's respond.";
public Server(ServerSocket server){
System.out.println("Server created.\nWaiting for client to connect...");
while(!server.isClosed()){
try {
Socket client = server.accept();
System.out.println("Connect Prot:" + client.getPort());
ReceiveMSG(client);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private void ReceiveMSG(final Socket socket) {
Thread threadReceive = new Thread(new Runnable() {
public void run() {
try {
while(socket.isConnected()){
DataInputStream dataIN = new DataInputStream(socket.getInputStream());
msgIN = dataIN.readUTF();
if(!msgIN.isEmpty())RespondMSG(socket);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
threadReceive.start();
}
private void RespondMSG(final Socket socket){
try {
DataOutputStream dataOUT = new DataOutputStream(socket.getOutputStream());
dataOUT.writeUTF(msgOUT);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args) throws Exception{
ServerSocket server = new ServerSocket(5678);
new Server(server);
}
}
答案 0 :(得分:0)
server.accept()为每个连接创建socket的新实例(读取ServerSocket的Javadoc)。因此,两个线程将并行运行,每个线程处理来自不同套接字的输入。
答案 1 :(得分:0)
在我看来,你是混淆变量和实际线程。您的代码有效,因为每次接受新连接时,都会创建一个全新的线程并开始为其提供服务。 threadReceive
只是一个局部变量名,而不是线程的名称。您可以使用它来创建封装Thread的新Runnable,然后启动它。在变量threadReceive
超出范围后,线程仍然在后台运行,它不会受到影响。
考虑以下示例:
public class ThreadTest
{
public static void main(String[] args)
{
for(int i = 0; i < 10; i++)
{
Thread thread = new Thread(new Runnable()
{
public void run()
{
System.out.println("Hello from thread " +
Thread.currentThread().getName());
}
});
thread.setName("MyThread-" + i);
thread.start();
}
}
}
使用名为thread
的相同局部变量,创建并启动10个单独的线程。线程并行运行,并不总是按照创建和启动的顺序运行,但不受超出范围的局部变量的影响。为变量分配new Thread
对Thread先前引用的变量没有影响。
Hello from thread MyThread-1
Hello from thread MyThread-3
Hello from thread MyThread-8
Hello from thread MyThread-9
Hello from thread MyThread-0
Hello from thread MyThread-4
Hello from thread MyThread-2
Hello from thread MyThread-7
Hello from thread MyThread-6
Hello from thread MyThread-5