需求:多个线程使用一个类的静态变量:socket对象,需要保证每一个线程使用到的socket对象都是一样的,某一个线程修改,其他线程也同步修改
一、ConnectUtils.java 共享对象为 private static Socket instance;
在该类中使用instance时,直接引用,不可通过getInstanceSocket()获取,否则不能多线程共享socket变量
/** * 连接读写器的socket对象 */ public class ConnectUtils { static Properties prop = ConfigPropertiesUtil.getConfig("config.properties"); private static final Logger log = LoggerFactory.getLogger(ConnectUtils.class); //类初始化时,不初始化这个对象(延时加载,真正用的时候再创建) private static Socket instance; //构造器私有化 private void Socket() { } //方法同步,调用效率低 ConnectUtils.getInstanceSocket().sendUrgentData(0xFF); public static Socket getInstanceSocket() throws IOException { return instance; } /** * 判断socket对象是否处于连接状态 * * @return */ public static boolean checkConnet() { try { //Socket socket = getInstanceSocket(); if (instance == null) { log.debug("与读卡器未连接过,socket is null "); return false; } instance.sendUrgentData(0xFF); log.debug("与读卡器连接正常 " ); return true; } catch (IOException e) { log.debug("与读卡器已断开连接"); //System.out.println(e.getMessage());//"Connection timed out: connect" Socket is not connected Connection reset by peer: send e.printStackTrace(); } return false; } /** * 连接读卡器 * * @return */ public static boolean connet() { String ip = prop.getProperty("common.rfidIP"); int port = Integer.parseInt(prop.getProperty("common.rfidPort")); log.debug("开始请求连接读卡器,ip=" + ip + ";port=" + port); try { //Socket socket = ConnectUtils.getInstanceSocket(); instance = new Socket(ip, port); log.debug("请求连接读卡器成功"); return true; } catch (IOException ioException) { log.debug("请求连接读卡器异常"); ioException.printStackTrace(); } return false; } }