package javasrc.thread;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
*
* @author PC504
* 网络服务器模型,一旦有客户端连接到该服务器,
* 则启动一个新线程为该连接服务,服务内容为往客户端输送一些字符信息
* 1. 建立监听端口,创建线程池。
* 2. 发现有新连接,使用线程池来执行服务任务。
* 3. 服务完毕,释放线程到线程池
*
*/
public class ThreadUtil {
private static final int PORT = 19527;
private ServerSocket serverSocket = null;
private ExecutorService pool = null;
public static void main(String[] args) {
//
ThreadUtil tu = new ThreadUtil();
tu.start();
}
public void start(){
try {
//新建了一个线程池,线程池里面有 3 个线程为任务队列服务.如果在关闭前的执行期间由于失败而导致任何线程终止,那么一个新线程将代替它执行后续的任务
pool = Executors.newFixedThreadPool(3);
serverSocket = new ServerSocket(PORT); //ServerSocket 对象来初始化监听端口
serverSocket.setReuseAddress(true);
System.out.println("I'm listening");
while(true){
Socket socket = serverSocket.accept(); //当有新连接建立时,accept 返回时,将服务任务提交给线程池执行
pool.execute(new ServiceThread(socket));
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
cleanup();
}
public void cleanup() {
if (null != serverSocket) {
try {
System.out.println("serverSocket.close()");
serverSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//serverThreadPool.shutdown();
pool.shutdown();
}
}
package javasrc.thread;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.Serializable;
import java.net.Socket;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.locks.ReentrantLock;
public class ServiceThread implements Runnable , Serializable{
/**
* protocol xieyi layer independent duyi
*/
private static final long serialVersionUID = 1L;
private static ReentrantLock lock = new ReentrantLock();
private Socket socket = null;
private static int count = 0;
public static int getCount() {
int ret = 0;
try {
lock.lock();
ret = count;
} catch (Exception e) {
// TODO: handle exception
lock.unlock();
}
return ret;
}
private void increaseCount(){
try{
lock.lock();
++count;
}finally{
lock.unlock();
}
}
public ServiceThread(){
}
public ServiceThread(Socket socket){
this.socket = socket;
}
public void run() {
increaseCount();
int curCount = getCount();
String helloString = "hello, id = " + curCount + "\r\n";
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<String> future = executor.submit(new TimeConsumingTask());//Future 表示异步计算的结果
DataOutputStream dos = null;
try {
dos = new DataOutputStream(this.socket.getOutputStream());
dos.write(helloString.getBytes());
try {
dos.write("let's do soemthing other.\r\n".getBytes());
String result = future.get();
dos.write(result.getBytes());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (null != this.socket) {
try {
this.socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (null != dos) {
try {
dos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
executor.shutdown();
}
}
}
class TimeConsumingTask implements Callable<String> {
public String call() throws Exception {
System.out.println("It's a time-consuming task,you'd better retrieve your result in the furture");
return "ok, here's the result: It takes me lots of time to produce this result";
}
}
在客户端cmd 下运行 telnet 127.0.0.1 19527