serverthreadfactory.java
来自「JAVA实现的网络服务器文件同步」· Java 代码 · 共 98 行
JAVA
98 行
package com.msd;
import java.net.ServerSocket;
import java.util.HashMap;
public class ServerThreadFactory {
private String serverAddress = null;
private int threadNum = 0;
private int port = 0;
private int soTimeout = 0;
private ServerSocket server = null;
private static ServerThreadFactory instance = null;
private HashMap threadManager = null;
private int keyNum = 0;
//-------------------------构造器----------------------------//
private ServerThreadFactory(String _serverAddress,int _threadNum,int _port,int _soTimeout) {
this.serverAddress = _serverAddress.trim();
this.threadNum = _threadNum;
this.port = _port;
this.soTimeout = _soTimeout;
this.threadManager = new HashMap(5);
try {
this.server = new ServerSocket(port,5);
} catch(Exception e) {
Log.logger.error("ServerThreadFactory client ServerSocket init error: " + e);
}
}
public synchronized static void create(String _serverAddress,int _threadNum,int _port,int _soTimeout) {
if(instance == null)
instance = new ServerThreadFactory(_serverAddress,_threadNum,_port,_soTimeout);
}
public static ServerThreadFactory getInstance() {
if(instance == null)
throw new NullPointerException("ServerThreadFactory is null");
return instance;
}
//-------------------------END----------------------------------//
//=========================INIT=================================//
public void init() {
for(int i=0;i<threadNum;i++)
addThread();
startServer();
}
//=========================END==================================//
//-------------------------服务监听线程-------------------------//
private void startServer() {
ServerThread cst = new ServerThread(server,serverAddress);
Thread t = new Thread(cst);
t.start();
}
public void ExceptionServerOut() {
startServer();
}
//-------------------------END----------------------------------//
//=========================功能线程=============================//
public synchronized boolean isRunning(String key) {
int t = threadManager.size();
if(threadNum == t) {
return true;
} else if(threadNum > t) {
addThread();
return true;
} else {
removeThread(key);
return false;
}
}
private void addThread() { //增加线程
StringBuffer keybf = new StringBuffer("T");
keybf.append(keyNum);
String key = keybf.toString();
InceptThread inth = new InceptThread(key,soTimeout);
Thread t = new Thread(inth);
t.start();
threadManager.put(key,inth);
keyNum++;
}
private void removeThread(String key) { //减少线程
threadManager.remove(key);
}
public synchronized void ExceptionOut(String key) {
removeThread(key);
if(threadManager.isEmpty()) {
addThread();
}
}
//=========================END==================================//
}
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?