用 java 的 List<> 对象管理客户端连接的服务线程

并发编程运行的时候,每次创建一个新的线程需要消耗大量的时间,这时,我考虑到能不能使用List<>来管理已经创建的线程,当连接断开后,服务线程只是挂起。在新连接请求时,如果有挂起的服务线程,直接为新连接服务。


// 采用List<>管理多线程,使用suspend()函数  
import java.io.*;  
import java.net.*;  
import java.util.*;  
public class NewNewMTEchoServer {  
    public static void main(String[] args)throws Exception {  
        if (args.length != 1) {  
            System.out.println("用法:MTServer <端口号>");  
            return ;  
        }  
        ServerSocket ss = new ServerSocket(Integer.parseInt(args[0]));  
        System.out.println("服务程序正在监听端口:" + args[0]);  
        List<NewEchoThread> threads = new ArrayList<>();  
        for (;;) {  
            boolean flag = false;  
            Socket client = ss.accept();  
            for (NewEchoThread t : threads) {  
                if (t.isSuspended()) {  
                    t.setSocket(client);  
                    System.out.println("这是第" + threads.indexOf(t) + "个线程");  
                    t.resumeRequest();  
                    flag = true;  
                    break;  
                }  
            }  
            if (!flag) {  
                NewEchoThread temp = new NewEchoThread(client);  
                threads.add(temp);  
                System.out.println("这是第" + threads.indexOf(temp) + "个线程");  
                temp.start();  
            }  
        }  
    }  
}  
  
class NewNewEchoThread extends Thread {  
    boolean isSuspended = false;  
    Socket socket;  
    NewNewEchoThread(Socket s) {  
        socket = s;  
    }  
    public void run() {  
        while (true) {  
  
            System.out.println("正在为客户程序提供服务:" + socket);  
            try {  
                PrintWriter out = new PrintWriter(socket.getOutputStream(), true);  
                BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));  
                String message;  
                while ((message = in.readLine()) != null) {  
                    System.out.println(socket + "请求:" + message);  
                    out.println(message.toUpperCase());  
                }  
                out.close();  
                in.close();  
                socket.close();  
            } catch (IOException exc) {  
                exc.printStackTrace();  
            } finally {  
                <span style="white-space:pre">    </span>suspendRequest();  
                suspend();  
            }  
        }  
    }  
  
    public void setSocket(Socket s) {  
        socket = s;  
    }  
  
    public boolean isSuspended() {  
        return isSuspended;  
    }  
  
    public void suspendRequest() {    
        isSuspended = true;    
    }    
    
    public void resumeRequest() {    
        isSuspended = false;    
    }  
  
    private void waitWhileSuspended() throws InterruptedException {  
        while ( isSuspended ) {  
            Thread.sleep(200);  
        }    
    }  
  
} 

考虑到Java已经推荐不再使用suspend()函数和resume()函数,因此修改为下面的代码:

// 采用List<>管理多线程,不使用suspend()函数   
import java.io.*;
import java.net.*;
import java.util.*;
public class NewMTEchoServer {
    public static void main(String[] args)throws Exception {
        if (args.length != 1) {
            System.out.println("用法:MTServer <端口号>");
            return ;
        }
        ServerSocket ss = new ServerSocket(Integer.parseInt(args[0]));
        System.out.println("服务程序正在监听端口:" + args[0]);
        List<NewEchoThread> threads = new ArrayList<>();
        for (;;) {
        	boolean flag = false;
        	Socket client = ss.accept();
        	for (NewEchoThread t : threads) {
        		if (t.isSuspended()) {
        			t.setSocket(client);
        			System.out.println("这是第" + threads.indexOf(t) + "个线程");
        			t.resumeRequest();
        			flag = true;
        			break;
        		}
        	}
        	if (!flag) {
        		NewEchoThread temp = new NewEchoThread(client);
        		threads.add(temp);
        		System.out.println("这是第" + threads.indexOf(temp) + "个线程");
        		temp.start();
        	}
        }
    }
}

class NewEchoThread extends Thread {
	boolean isSuspended = false;
    Socket socket;
    NewEchoThread(Socket s) {
        socket = s;
    }
    public void run() {
        while (true) {

        	try {
        		waitWhileSuspended();
        	} catch (InterruptedException exc) {
        		exc.printStackTrace();
        	}

        	System.out.println("正在为客户程序提供服务:" + socket);
        	try {
            	PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
            	BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            	String message;
            	while ((message = in.readLine()) != null) {
            	    System.out.println(socket + "请求:" + message);
            	    out.println(message.toUpperCase());
            	}
            	out.close();
            	in.close();
            	socket.close();
        	} catch (IOException exc) {
            	exc.printStackTrace();
        	} finally {
        		suspendRequest();
        	}
        }
    }

	public void setSocket(Socket s) {
		socket = s;
	}

	public boolean isSuspended() {
		return isSuspended;
	}

    public void suspendRequest() {  
        isSuspended = true;  
    }  
  
    public void resumeRequest() {  
        isSuspended = false;  
    }

    private void waitWhileSuspended() throws InterruptedException {
        while ( isSuspended ) {
            Thread.sleep(200);
        }  
    }

}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值