很多操作系统支持多个线程同时调用Socket.accept()方法,上述程序可以简化为:class PreAllocation
{
private static int PORT = 80;
private static int N = 12;
public static void main(String args[]) throws Exception
{
new PreAllocation();
}
private java.net.ServerSocket m_server;
private class Slave extends Thread
{
public void run()
{
java.net.Socket sock = m_server.accept();
//todo:... 同上面部分
}
}
public PreAllocation() throws Exception
{
m_server = new java.net.ServerSocket(PORT);
for(int i=0; i<N; i++)
new Slave().start();
this.wait(); //这一句使master thread自身进入死锁,在很多操作系统中,主线程退出将导致从线程也退出,如果是运行在win32s中,这一句可以去掉
}
}
{
private static int PORT = 80;
private static int N = 12;
public static void main(String args[]) throws Exception
{
new PreAllocation();
}
private java.net.ServerSocket m_server;
private class Slave extends Thread
{
public void run()
{
java.net.Socket sock = m_server.accept();
//todo:... 同上面部分
}
}
public PreAllocation() throws Exception
{
m_server = new java.net.ServerSocket(PORT);
for(int i=0; i<N; i++)
new Slave().start();
this.wait(); //这一句使master thread自身进入死锁,在很多操作系统中,主线程退出将导致从线程也退出,如果是运行在win32s中,这一句可以去掉
}
}
1.可以避免创建/销毁线程的操作系统开销
2.可以控制同时连接的数目(最高为N)