JavaSocket通信技术收发线程互斥的解决方法
考试吧 2010/4/14 字号:T T
Java Socket通信技术在很长的时间里都在使用,在不少的程序员眼中都有很多高的评价。那么下面我们就看看如何才能掌握这门复杂的编程语言,希望大家在今后的Java Socket通信技术使用中有所收获。
下面就是Java Socket通信技术在解决收发线程互斥的代码介绍。
package com.bill99.svr;
2.import java.io.IOException;
3.import java.io.InputStream;
4.import java.io.OutputStream;
5.import java.net.InetSocketAddress;
6.import java.net.Socket;
7.import java.net.SocketException;
8.import java.net.SocketTimeoutException;
9.import java.text.SimpleDateFormat;
10.import java.util.Date;
11.import java.util.Properties;
12.import java.util.Timer;
13.import java.util.TimerTask;
14.import java.util.concurrent.ConcurrentHashMap;
15.import java.util.concurrent.TimeUnit;
16.import java.util.concurrent.locks.Condition;
17.import java.util.concurrent.locks.ReentrantLock;
18.import org.apache.log4j.Logger;
19./**
20.*
title: socket通信包装类
21.*
Description:
22.*
CopyRight: CopyRight (c) 2009
23.*
Company: 99bill.com
24.*
Create date: 2009-10-14
25.*author sunnylocus
26. * v0.10 2009-10-14 初类
27.* v0.11 2009-11-12 对命令收发逻辑及收发线程互斥机制进行了优化,
处理命令速度由原来8~16个/秒提高到25~32个/秒
28.*/ public class SocketConnection {
29.private volatile Socket socket;
30.private int timeout = 1000*10; //超时时间,初始值10秒
31.private boolean isLaunchHeartcheck = false;//是否已启动心跳检测
32.private boolean isNetworkConnect = false; //网络是否已连接
33.private static String host = "";
34.private static int port;
35.static InputStream inStream = null;
36.static OutputStream outStream = null;
37.private static Logger log =Logger.getLogger
(SocketConnection.class);
38.private static SocketConnection socketConnection = null;
39.private static java.util.Timer heartTimer=null;
40.//private final Map recMsgMap= Collections.
synchronizedMap(new HashMap());
41.private final ConcurrentHashMap recMsgMap
= new ConcurrentHashMap();
42.private static Thread receiveThread = null;
43.private final ReentrantLock lock = new ReentrantLock();
44.private SocketConnection(){
45.Properties conf = new Properties();
46.try {
47.conf.load(SocketConnection.class.getResourceAsStream
("test.conf"));
48.this.timeout = Integer.valueOf(conf.getProperty("timeout"));
49.init(conf.getProperty("ip"),Integer.valueOf
(conf.getProperty("port")));
50.} catch(IOException e) {
51.log.fatal("socket初始化异常!",e);
52.throw new RuntimeException("socket初始化异常,请检查配置参数");
53.}
54.}
55./**
56.* 单态模式
57.*/
58.public static SocketConnection getInstance() {
59.if(socketConnection==null) {
60.synchronized(SocketConnection.class) {
61.if(socketConnection==null) {
62.socketConnection = new SocketConnection();
63.return socketConnection;
64.}
65.}
66.}
67.return socketConnection;
编辑推荐:
温馨提示:因考试政策、内容不断变化与调整,长理培训网站提供的以上信息仅供参考,如有异议,请考生以权威部门公布的内容为准! (责任编辑:长理培训)
点击加载更多评论>>