java创建线程池适用于TCP短连接场景
import java.util.LinkedList;
import java.util.concurrent.atomic.AtomicLong;
/**
* Copyright ©2017 gonglibin
* 守护线程池类接收并执行任务
* @author gonglibin
* 2017.03.28
*/
public class TuPool {
private final int TU_TSKSIZE = 2;
private final String TU_TSKNAME = "TuPool";
private int num = TU_TSKSIZE;
private LinkedList tsk = new LinkedList();
/**
* 工作者内部类
* 用于处理任务
*/
private class TuWork implements Runnable {
public void run() {
while (true) {
TuTask one = null;
synchronized (tsk) {
while (true == tsk.isEmpty()) {
try {
tsk.wait();
} catch (Exception e) {
return;
}
}
one = tsk.removeFirst();
}
if (null != one) {
one.run();
}
}
}
}
public TuPool() {TuPoolInit();}
public TuPool(int n) {num = n; TuPoolInit();}
public void TuPoolCall(TuTask t) {
synchronized (tsk) {
tsk.addLast(t);
tsk.notify();
}
return;
}
private void TuPoolInit() {
AtomicLong tid = new AtomicLong();
for (int idx = 0; idx < num; idx ++) {
new Thread(new TuWork(), TU_TSKNAME + "-" + tid.incrementAndGet()).start();
}
return;
}
}
import java.net.Socket;
import java.io.PrintWriter;
import java.net.ServerSocket;
/**
* Copyright ©2017 gonglibin
* 被线程池分配执行具体业务
* @author gonglibin
* 2017.03.28
*/
public class TuServer {
private static final int TU_PKGSIZE = 1024;
private static final int TU_SERPORT = 8080;
private static final String TU_SERHEAD = "HTTP/1.1 200 OK\r\nServer: TuServer\r\nContent-Type: text/html;charset=UTF-8\r\nContent-Length: %d\r\n\r\n";
private static final String TU_SERBODY = "<title>test page</title><h1>图片一</h1><h1>图片二</h1><h1>图片三</h1>";
private static TuPool hdl = new TuPool();
private static class TuHandler implements Runnable {
private Socket skt;
public TuHandler(Socket s) {skt = s;}
public void run() {
PrintWriter err = null;
byte[] pkg = new byte[TU_PKGSIZE];
try {
err = new PrintWriter(skt.getOutputStream());
skt.getInputStream().read(pkg);
skt.getOutputStream().write((String.format(TU_SERHEAD, TU_SERBODY.getBytes().length) + TU_SERBODY).getBytes());
} catch (Exception e) {
err.println("HTTP/1.1 500");
err.println("");
err.flush();
} finally {
try {
err.close();
skt.close();
} catch (Exception e) {}
}
return;
}
}
public static void TuServerRun() throws Exception {
Socket cli = null;
ServerSocket ser = new ServerSocket(TU_SERPORT);
while (null != (cli = ser.accept())) {
hdl.TuPoolCall(new TuHandler(cli));
}
ser.close();
return;
}
}
/* 测试程序 */
public class TuSerTest {
public static void main(String[] args) throws Exception {
TuServer.TuServerRun();
return;
}
}
