学生我作业交完了,代码分享一下!不多说什么了哈
服务器端ThreadServer
ThreadPool.java
package thread;
import java.util.LinkedList;
public class ThreadPool extends ThreadGroup{
private boolean isClosed=false;//线程池是否关闭
private LinkedList<Runnable> workQueue;//表示工作队列
private static int threadPoolID;//表示线程池ID
private int threadID;//表示工作线程ID
public ThreadPool(int poolSize){//poolSize指定线程池中的工作线程数
super("ThreadPool-"+(threadPoolID++));
setDaemon(true);
workQueue=new LinkedList<Runnable>();//创建并启动工作线程
for(int i=0;i<poolSize;i++){
new WorkThread().start();
}
}
/**
*向工作队列中加入一个新任务,由工作线程去执行
* @param task
*/
public synchronized void execute(Runnable task){
if(isClosed){//线程池被关闭则抛出
throw new IllegalStateException();
}
if(task!=null){
workQueue.add(task);
notify();//唤醒正在getTask()方法中等待任务的工作线程
}
}
/**
* 从工作队列中取出一个任务,工作线程会调用此方法
* @return
* @throws InterruptedException
*/
protected synchronized Runnable getTask()throws InterruptedException{
while (workQueue.size()==0) {
if(isClosed)return null;
wait();//如果工作队列中没有任务,就等待任务
}
return workQueue.removeFirst();
}
/**
* 关闭线程池
*/
public synchronized void close(){
if(!isClosed){
isClosed=true;
workQueue.clear();//clean a workQueue
interrupt();//stop all of thread pool ID
}
}
/**
* 等待工作线程把所有任务执行完
*/
public void join(){
synchronized (this) {
isClosed=true;
notifyAll();//唤醒还在getTask()方法中等待任务的工作线程
}
Thread[]thread=new Thread[activeCount()];
int count =enumerate(thread);//获得当前所有或者的工作线程
for (int i = 0; i <count; i++) {//等待所有的线程运行起来
try {
thread[i].join();//等待所有工作线程运行结束
} catch (InterruptedException e) {
// TODO: handle exception
}
}
}
/**
* 工作线程
*
* @author Mouse
*
*/
private class WorkThread extends Thread{
public WorkThread(){
//加入到当前TreadPool线程组中
super(ThreadPool.this,"WorkThread-"+(threadID++));
}
public void run(){
while (!isInterrupted()) {//判断线程是否被中断
Runnable task=null;
try {//取出任务
task=getTask();
} catch (InterruptedException e) {
// TODO: handle exception
}
if(task==null)return ;//如果getTask()返回Null或者线程执行getTask()被中断,则结束此线程
try {//运行任务
task.run();
} catch (Throwable e) {
// TODO: handle exception
e.printStackTrace();
}
}
}
}
}
EchoServer.java
package thread;
import java.io.*;
import java.net.*;
/**
*
* @author Mouse
*
*/
public class EchoServer{
private int port=8000;
private ThreadPool threadPool;//线程池
private ServerSocket serverSocket;
private final int POOL_SIZE=4;//单个Cpu时线程池中工作的数目
public EchoServer()throws IOException{
serverSocket=new ServerSocket(port);
//创建线程池
//Rumtime的availableProcessors()方法返回当前系统的cup数目
//系统的cpu越多,线程池中的数目也越多
threadPool=new ThreadPool(Runtime.getRuntime().availableProcessors()*POOL_SIZE);
System.out.println("服务器启动!");
}
public void service(){
while (true) {
Socket socket=null;
try {
socket=serverSocket.accept();
threadPool.execute(new Handler(socket));//把与客户通讯的任务交给线程
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
}
public static void main(String args[])throws IOException{
new EchoServer().service();
}
}
//负责与单个客户通讯任务
class Handler implements Runnable{
private Socket socket;
public Handler(Socket socket){
this.socket=socket;
}
private PrintWriter getWriter(Socket socket)throws IOException{
OutputStream socketOut=socket.getOutputStream();
return new PrintWriter(socketOut, true);//参数为true表示每写一行,PrintWriter缓存就自动溢出,把数据写到目的
}
private BufferedReader getReader(Socket socket)throws IOException {
InputStream socketIn=socket.getInputStream();
return new BufferedReader(new InputStreamReader(socketIn));
}
public String echo(String msg){
return "echo:"+msg;
}
public void run(){
try {
//得到客户端的地址和端口号
System.out.println("New connection accepted"+socket.getInetAddress()+":"+socket.getPort());
BufferedReader br=getReader(socket);
PrintWriter pw=getWriter(socket);
String msg=null;
while ((msg=br.readLine())!=null) {
System.out.println(msg);
pw.println(echo(msg));
if(msg.endsWith("bye")){
break;
}
}
} catch (IOException e) {
// TODO: handle exception
e.printStackTrace();
}finally{
try {
if(socket!=null){
socket.close();
}
} catch (IOException e) {
// TODO: handle exception
e.printStackTrace();
}
}
}
}
客户端
EchoClient.java
package thread;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
public class EchoClient {
private String host="localhost";
private int port=8000;
private Socket socket;
Socket[]sockets=new Socket[1000];
public EchoClient()throws IOException{
// for(int i=0;i<1000;i++){
socket=new Socket(host,port);
// }
}
public static void main(String args[])throws IOException{
new EchoClient().talk();
}
private PrintWriter getWriter(Socket socket)throws IOException{
OutputStream socketOut=socket.getOutputStream();
return new PrintWriter(socketOut, true);
}
private BufferedReader getReader(Socket socket)throws IOException {
InputStream socketIn=socket.getInputStream();
return new BufferedReader(new InputStreamReader(socketIn));
}
public void talk()throws IOException{
try {
BufferedReader br=getReader(socket);
PrintWriter pw=getWriter(socket);
BufferedReader localReader=new BufferedReader(new InputStreamReader(System.in));
String msg=null;
while ((msg=localReader.readLine())!=null) {
pw.println(msg);
System.out.println(br.readLine());
if(msg.equals("bye")){
break;
}
}
} catch (IOException e) {
// TODO: handle exception
e.printStackTrace();
}finally{
try {
socket.close();
} catch (IOException e2) {
// TODO: handle exception
e2.printStackTrace();
}
}
}
}
代码的链接地址:http://download.csdn.net/detail/u010343650/9448391
这篇博客分享了一个使用Java线程池处理Socket并发通讯的作业解决方案,包括服务器端ThreadServer和客户端EchoClient的代码实现。
413

被折叠的 条评论
为什么被折叠?



