菜鸟一枚,如果问题问的不恰当请各位轻喷。
第二次编辑:抱歉各位!我似乎误导了大家!
在学习客户端与服务器端的通信时,当中这么一段代码:
while(true){
//等待客户端的连接
socket = serverSocket.accept();
//创建一个新的线程
ServerThread serverThread = new ServerThread(socket);
//启动线程
serverThread.start();
}
我想问:为什么一个同名对象能一直被new出来(当客户端建立起一个连接时)?比如这个serverThread。
但是如果我这么写:
while(true){
//等待客户端的连接
socket = serverSocket.accept();
//创建一个新的线程
ServerThread serverThread = new ServerThread(socket);
ServerThread serverThread = new ServerThread(socket);
//启动线程
serverThread.start();
}
我知道这是错的,new相同名字的对象是不可以的。
但是在无限循环中,也是在不停的new出对象啊,ServerThread serverThread = new ServerThread(socket);
不停的被执行,serverThread不停的创建..这样为什么可以呢?
Objects have scope. For example, the serverThread in the first loop will be destroyed when the loop ends. That is, it belongs to the same role between "{" and "}" in while (true) {...} domain.
C language is block scope, as long as you write a
{ }
就会生成一级作用域。所以serverThread
local variable similar to a function. Each loop is a different call to the function, so there won't be any problems.Each loop can be used as a scope. The second one is that there are two identical variable names in the same scope, which is definitely not possible.
Just change the name of the second variable.
Supplement: Your variable is a local variable inside the loop. You can think of it this way: this loop and the next loop are not in the same scope, so you essentially created the same name in different scopes. variable.
In fact, this is just a repeated variable declaration error
If you say this, it is the same as what everyone said. The serverThread variable will actually be destroyed after a loop. When you come to
ServerThread serverThread = new ServerThread(socket);
, serverThread actually no longer exists, so it can be Restate
A variable that already exists in the same scope cannot be declared repeatedly, but this is possible:
Class A{
Int a = 0;
void methodB(){
}
}