正在使用Java学习多线程套接字编程:
请看这段代码:
ServerSocket server=new ServerSocket(8888);
while(true){
counter++;
Socket serverClient=server.accept();
Threads t = new Threads(serverclient)
}
在这里,我们为每个连接创建一个Threads对象(具有已实现Runnable接口的类)。
我的查询是: 我们不是在创建新对象,而是使用新值重新初始化同一对象。 因此,在重新初始化新的对象引用之后,应该删除旧的对象引用
因此创建了这段代码以了解Java中的构造函数。
public class free_memory
{
public static void main(String args [])
{ int i;
long UsedMem=Runtime.getRuntime().totalMemory()-Runtime.getRuntime().freeMemory();
System.out.println("Total memory used before execution : " + UsedMem / 1024);
new temp();
UsedMem=Runtime.getRuntime().totalMemory()-Runtime.getRuntime().freeMemory();
System.out.println("Total memory used after execution of 1 constructor: " + UsedMem/ 1024);
for(i=0;i<10;i++)
{
new temp();
}//for
UsedMem=Runtime.getRuntime().totalMemory()-Runtime.getRuntime().freeMemory();
System.out.println("Total memory used after execution of 10 constructor: " + UsedMem/ 1024);
for(i=0;i<10;i++)
{
temp a = new temp();
}//for
UsedMem=Runtime.getRuntime().totalMemory()-Runtime.getRuntime().freeMemory();
System.out.println("Total memory used after execution of 10 constructor: " + UsedMem/ 1024);
int a;
UsedMem=Runtime.getRuntime().totalMemory()-Runtime.getRuntime().freeMemory();
System.out.println("Allocating an integer: " + UsedMem/ 1024);
}//main
}
class temp
{
int a[] = new int[10];
int i;
temp()
{
for(i=0;i<10;i++)
{
a[i] = 10;
}//for
}//constructor
}//class
输出为:
Total memory used before execution : 1599
Total memory used after execution of 1 constructor: 2048
Total memory used after execution of 10 constructor: 2048
Total memory used after execution of 10 constructor: 2048
Allocating an integer: 2048
此代码未分配任何额外的内存。
能请你帮忙吗 我们应该创建一个对象数组
//我的建议应该是这样的:
Socket serverClient=server.accept();
Threads t[i] = new Threads(serverclient)
//原始代码
Socket serverClient=server.accept();
Threads t = new Threads(serverclient)
预先感谢