67,513
社区成员
发帖
与我相关
我的任务
分享
public class BIOTest {
public static void main(String[] args) throws IOException {
ExecutorService eService= new ThreadPoolExecutor(
1,
Runtime.getRuntime().availableProcessors(),
5,
TimeUnit.SECONDS,
new LinkedBlockingQueue<Runnable>(3),
Executors.defaultThreadFactory(),
new ThreadPoolExecutor.AbortPolicy()
);
ServerSocket sSocket=new ServerSocket(9527);
System.out.println("服务开始");
while(true) {
//监听
final Socket socket=sSocket.accept();
System.out.println("有人进来了");
eService.execute(()->{
handler(socket);
});
}
}
public static void handler(Socket socket) {
try {
// System.out.println("当前线程为:"+Thread.currentThread().getName());
byte[] bytes=new byte[1024];
InputStream inp =socket.getInputStream();
while(true) {
int read = inp.read(bytes);
if(read!=-1) {
System.out.println(Thread.currentThread().getName()+":"+new String(bytes,0,read));
}else {break;}
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}finally {
System.out.println(Thread.currentThread().getName()+" OUT");
try {
socket.close();
} catch (Exception e2) {
// TODO: handle exception
e2.printStackTrace();
}
}
}
}