⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 serverthreadpoolbuilder.java

📁 JAVA实现的聊天工具,可以容纳最多10个用户 1.本系统需要JDK1.5 或更高版本的支持。 2.serverDatabase为服务器端的数据文件. 若使用现有数据,可用帐号:1, 密码
💻 JAVA
字号:
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.*;
public class ServerThreadPoolBuilder implements Runnable{
	private ServerSocket serverSocket = null;
	private Socket tempSocket=null;
	private static boolean signal = true;
	private boolean initiate;
	private int threadPoolSize;
	private Thread[] threadPool;
	private Thread controlThread; //because listen on port can fail,so ServerControlGUI is to be started here,
								 //receiving argument indicating listen on port fail or not
	private Administrator currentAdm; //to pass to ServerControlGUI
	private static ExecutorService tpes;
	
	public ServerThreadPoolBuilder(int threadPoolSize,Administrator currentAdm){
		this.threadPoolSize=threadPoolSize;
		this.currentAdm=currentAdm;
		initiate=true;
	}
	
	public void run(){
		//System.out.println("pool builder!");
		setupThreadsPool();
		listen();
	}
	
	static void exit(){
		//controlThread.stop();
		signal=false;
		tpes.shutdown();
		Server.exit();
	}
	//thread pool to handle request from clients
	private void setupThreadsPool(){ //initial threads in thread pool and excecute every thread
    	//System.out.println("to setup pool");
    	tpes = Executors.newFixedThreadPool(threadPoolSize);
    	if(tpes==null) System.out.println("!!null");
		threadPool = new Thread[threadPoolSize];
		for(int i=0;i<threadPoolSize;i++){
			ServerThread clientHandler=new ServerThread();
			threadPool[i]=new Thread(clientHandler , "ServerThread"+i);
			tpes.execute(threadPool[i]);
		}
    }
    
    private void listen(){
    	try{
            serverSocket = new ServerSocket(4444); //setup server socket
        }catch (IOException e) {
            //System.err.println("Could not listen on port: 4444.");
        	initiate=false; //listen on port fail
        }        
        controlThread=new Thread(new ServerControlGUI(currentAdm,initiate),"ServerControlThread");        
    	controlThread.start();
        
    	if(!initiate)
    		return;
    	//System.out.println("to listen on port 4444");
        while(signal){
        	try{
        		tempSocket=serverSocket.accept();
        	}catch(IOException e){
        		System.out.println(e+" Server "+e.getMessage());
        	}
        	ServerThread.processRequest(tempSocket);
        }
    }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -