2 be proud Be_Proud 于 2016.03.10 13:39 提问

关于java并发编程,完整代码

谁能给个完整的 、有关java 并发编程的例子?多个客户端向服务器传输数据

3个回答

caozhy
caozhy   Ds   Rxr 2016.03.10 14:25
已采纳
wojiushiwo945you
wojiushiwo945you   Ds   Rxr 2016.03.10 13:46

最简单的就是Java Web项目啊,Tomcat处理请求就是用的多线程处理的。

Be_Proud
Be_Proud 并不是Java Web
接近 2 年之前 回复
lx624909677
lx624909677   Ds   Rxr 2016.03.10 23:00
 import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.apache.log4j.Logger;
import Smart.Java.Com.Constant;
import Smart.Java.Com.StringHandler;
//c:\jdk1.5\bin\java -classpath c:\jdk1.5 SocketServerThread
public class SocketServer {
 private static Logger logger = Logger.getLogger(SocketServer.class);

 private ServerSocket serverSocket;
 private ExecutorService executorService;//线程池
    private final int POOL_SIZE=10;//单个CPU线程池大小
 public SocketServer(){
  try
  {
   serverSocket = new ServerSocket(Constant.SocketPort);
   executorService=Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()*POOL_SIZE);
   System.out.println("监听服务器启动,端口号:" + Constant.SocketPort);
  }
  catch(Exception e)
  {
   String s = "监听服务器启动 失败,可能是端口" + Constant.SocketPort + "已被占用,请重置端口" + Constant.SocketPort + "后重试";
   logger.error(e.getMessage() + "<br />" + s);
   //System.out.println();
  }
 }
 public void service() {
  try
  {
   while (true) {
    Socket clientSocket=null;
    try {
     // 接收客户连接,只要客户进行了连接,就会触发accept();从而建立连接
     clientSocket = serverSocket.accept();
     executorService.execute(new SocketHandler(clientSocket));
    } catch (Exception e) {
     logger.error(StringHandler.GetException(e));
     e.printStackTrace();
    }
   }
  }
  catch (Exception e1) {
   //logger.error(StringHandler.GetException(e1));
   //e1.printStackTrace();
  }
  finally
  {
   if (serverSocket != null)
   {
    try
    {
     serverSocket.close();
    }catch(Exception ex1){}
   }
  }
 }
 public static void main(String[] args) throws Exception {
  try
  {
   new SocketServer().service();
  }
  catch(Exception ex)
  {
   logger.error(StringHandler.GetException(ex));
   ex.printStackTrace();
  }
 }
} 
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import org.apache.log4j.Logger;
import Smart.Java.Com.Constant;
import Smart.Java.Com.MonitorHandler;
import Smart.Java.Com.StringHandler;
//public class SocketHandler implements Runnable {
public class SocketHandler implements Runnable{
 private static Logger logger = Logger.getLogger(SocketHandler.class);

 private Socket socket;
 public SocketHandler(Socket socket) {
  this.socket = socket;

//  run();
 }
 private PrintWriter getWriter(Socket socket) throws Exception {
  OutputStream socketOut = socket.getOutputStream();
  return new PrintWriter(socketOut, true);
 }
// private BufferedReader getReader(Socket socket) throws Exception {
//  
// }


 private String GetInfoByAction(String _args)
 {
  try
  {
   String returnStr = "";
   String[] ssArgs = _args.split(";");
   String _productSeries = ssArgs[0];
   String _ciKey = ssArgs[1];
   if (_productSeries.equals("") || _ciKey.equals(""))
   {
    return "0";
   }
   String _ip = ssArgs[2];
   String _port = ssArgs[3];
   String _username = "";
   String _pwd = "";

   if (ssArgs.length > 4)
   {
    _username = ssArgs[4];
    if (ssArgs.length > 5)
    {
     _pwd = ssArgs[5];
    }
   }

   MonitorHandler monitor = new MonitorHandler(_productSeries, _ciKey, _ip, _port, _username, _pwd);

   returnStr = monitor.GetMonitorInfo();

   return returnStr;
  }
  catch (Exception e)
  {
   e.printStackTrace();
   logger.error(StringHandler.GetException(e));
   return Constant.ErrorNumber_UnkownException;
  }
 }

 private static String GetCurrentTime()
 {
  try
  {
   Calendar cal = Calendar.getInstance();   
   SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
   String time = formatter.format(cal.getTime());  
   return time;
  }
  catch(Exception ex)
  {
   ex.printStackTrace();
   logger.error(StringHandler.GetException(ex));
   return "";
  }
 }
 public void run() {
  try {
   //得到客户端发送的信息
   BufferedReader br = null;
   InputStream socketIn = socket.getInputStream();

   br = new BufferedReader(new InputStreamReader(socketIn));
   String actionInfo = "";
   try
   {
    actionInfo = br.readLine();
   }
   catch(Exception ex){}
   while (actionInfo != null)
   {
    System.out.println(GetCurrentTime() + "收到来自【" + socket.getInetAddress() + ":" + socket.getPort() + "】的监听请求:" + actionInfo);
    if (actionInfo != null)
    {
     String str = GetInfoByAction(actionInfo);
     //返回信息给Client端
     PrintWriter pw = getWriter(socket);
     //System.out.println(str);
     pw.println(str);
    }
    actionInfo = br.readLine();
   }
  } catch (Exception e) {
   logger.error(StringHandler.GetException(e));
   e.printStackTrace();
  }
   finally {
   try {
    if (socket != null)
     socket.close();
   } catch (Exception e) {}
  }
 }
}
Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!